我有一种情况,我正在遍历json response并尝试具有映射的键值对。目标:遍历json文件,并在content1
对象内搜索名称为labels
的值,然后返回name
(TEST API1)和id
(33332)的对应值并将其存储在变量中或列表以将其进一步存储在格式为name
,id
和content
名称的csv文件中,并添加sl num
。
这是我已经尝试过的内容
get_metadata = requests.get('https://testurl.com)
metadata=get_metadata.json()
for key in metadata:
value = metadata[i]["labels"]
print("The key and value are ({}) = ({})".format(key, value))
#here error occurs
错误:TypeError: the JSON object must be str, bytes or bytearray, not list
我如何实现上述目标,应该有什么帮助的方法?如果有人可以帮助您,在这种情况下如何继续操作。
您可以尝试
>>> for key in metadata:
... name = key['name']
... label_info = key['labels']
... for x in label_info:
... print(f"{name}, {x['id']}, {x['content']}")
...
TEST API1, 667, content1
TEST API1, 668, content2
TEST API1, 669, content3
TEST API1, 112, content4
TEST API2, 668, content2
TEST API2, 669, content3
TEST API2, 112, content4
尝试这个:
for dict_ in metadata:
for label in dict_['labels']:
if label['content'] == 'content1':
print('The key and value are ({}) = ({})'.format(dict_['id'],
dict_['name']))
输出:
The key and value are (33332) = (TEST API1)