我有一个场景,我正在循环遍历 json response并尝试拥有映射的键值对。
目标:循环遍历 json 文件并在 labels
对象中搜索名为 content1
的值,如果找到则返回 name
的相应值(TEST API1) 和 id
(33332) 并将其存储在变量或列表中,以进一步将其存储在格式为 name
和 id
和 content
名称并添加 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))
这里发生错误:
Error: `TypeError: the JSON object must be str, bytes or bytearray,
not list`
我怎样才能实现上述目标,应该采取什么方法,任何帮助都会很好。 如果有人可以在这里提供帮助,如何在这种情况下进一步进行。
最佳答案
试试这个:
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)
如果您想将结果导出为 CSV
文件,请尝试以下操作:
import csv
with open('objects.csv', 'w') as csvfile:
filewriter = csv.writer(
csvfile,
delimiter=',',
quotechar='|',
quoting=csv.QUOTE_MINIMAL
)
for dict_ in metadata:
for label in dict_['labels']:
if label['content'] == 'content1':
filewriter.writerow([dict_['id'], dict_['name']])
关于python - 在json中循环并映射键值python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59452316/