Python 3.x 如何在Python中迭代JSON对象并获取密钥?

Python 3.x 如何在Python中迭代JSON对象并获取密钥?,python-3.x,Python 3.x,我有: {"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\u no”

我有:

{"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\u 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中要容易得多…

您可以迭代
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]})")

您期望的输出是什么?我想循环x['invoice\u no']['name'],如果这个元素=='blah blah',那么y=x['invoice\u no'][key']['start\u offset'],这不是输出-这是代码。非常感谢,但这不是键。这只是元素名和值。所以我有如果f“{list_item[keys]}”==“Invoice 21342”:以及如何从同一个对象获得“start_offset”?我需要指向此元素的指针。因此,如果我正确理解您的问题,您希望对象位于
name
=“Invoice 21342”,并获取所有其他属性,在这种情况下,您只需执行
如果list\u item[“name”]=“Invoice 21342”:
,那么
list\u item
将是您的intrest对象。是的,这就是我想要的-非常感谢你的帮助!