【问题标题】:How to parse dynamic json keys in python如何在python中解析动态json键
【发布时间】:2020-09-14 08:09:30
【问题描述】:

如何使用以下 json 解析动态数字键。我可以手动进行json_text['entities']['0']['uid'],如何动态迭代所有键并获取所有uid

{
    "entities": {
        "0":{
            "uid": "3769fcb3-8312-41b8-a5c9-3c24b6a9ce96"
            },
        "1":{
            "uid": "3769fcb3-8312-41b8-a5c9-3c24b6a9ce97"
            },
        "2":{
            "uid": "3769fcb3-8312-41b8-a5c9-3c24b6a9ce98"
            }
        "3":{
            ;
            }
          :
          :
          :           
    }   
}

代码:

import os, json
import pandas as pd

path_to_json = '/home/sshuser/data/'
json_files = [pos_json for pos_json in os.listdir(path_to_json) if pos_json.endswith('.json')]
print(json_files) 
# here I define my pandas Dataframe with the columns I want to get from the json

# we need both the json and an index number so use enumerate()
for index, js in enumerate(json_files):
    with open(os.path.join(path_to_json, js)) as json_file:
        json_text = json.loads(json_file.read())
        uids= json_text['entities']['0']['uid']
        print(seeMore)      

    

【问题讨论】:

    标签: python json python-3.x python-2.7


    【解决方案1】:

    你可以这样做

    import json
    
    with open ("yourfile.json","r") as f:
       json=json.load(f)
    try:
       a=0
       while True:
          print(json["entities"][str(a)]["uid"])
          a+=1
    except KeyError:
       pass
    

    【讨论】:

      【解决方案2】:

      json_text['entities'] 是一个字典。您可以使用 dict.items() 来迭代键值对。

      for key, value in json_text['entities'].items(): # assume key 'entities' always exists
          print(f"{key} --> {value.get('uid')}") 
      

      如果key 不重要,您可以直接迭代.values()

      for value in json_text['entities'].values():
          print(value.get('uid')) 
      

      【讨论】:

        猜你喜欢
        • 2021-11-12
        • 1970-01-01
        • 2021-05-18
        • 2014-12-22
        • 2011-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多