我有JSON:
{"invoice_no":[ {"name":"Invoice 21342","start_offset": "10", "end_offset": "25"},{"name":"Invoice No:","start_offset": "10", "end_offset": "25"}],"invoice_date":[ {"name":"From day","start_offset": "10", "end_offset": "25"}]}
我想遍历“invoice_no”对象,并获取该对象中每个项目的键。最终会有这样的东西:
jsonObject["invoice_no"][key]["name"]
jsonObject["invoice_no"][key]["start_offset"]
我不想只获取属性名称或值。我需要钥匙来配对
对于PHP,这是微不足道的,在Python中,我花了几个小时都没有成功。
编辑:在你的帮助下的最终代码:
import json
jsonString = '{"invoice_no":[ {"name":"Invoice 21342","start_offset": "35", "end_offset": "25"},{"name":"Invoice No:","start_offset": "10", "end_offset": "25"}],"invoice_date":[ {"name":"From day","start_offset": "10", "end_offset": "25"}]}'
jsonObject = json.loads(jsonString)
# get keys of jsonObject
for item in jsonObject:
# loop through each list
for list_item in jsonObject[item]:
if list_item['name'] == "Invoice 21342":
print (list_item['start_offset'])
在PHP中这要容易得多,多得多…
发布于 2019-11-28 02:12:05
您可以遍历jsonObject
的键,其中每一项的值都是一个列表。然后遍历每个字典列表并获得键值对。你可以这样做
# get keys of jsonObject
for item in jsonObject:
# loop through each list
for list_item in jsonObject[item]:
# for each list get the key,value pair
for keys in list_item:
print (f"(Key,Value)=>({keys}, {list_item[keys]})")
https://stackoverflow.com/questions/59074990
复制相似问题