添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

如何在python中解析动态json键

0 人关注

如何用以下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":{

Code:

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
marjun
marjun
发布于 2020-09-14
2 个回答
Salim Baskoy
Salim Baskoy
发布于 2020-09-14
已采纳
0 人赞同

你可以这样

import json
with open ("yourfile.json","r") as f:
   json=json.load(f)
   while True:
      print(json["entities"][str(a)]["uid"])
except KeyError:
    
buran
buran
发布于 2020-09-14
0 人赞同

json_text['entities'] 是一个dict。你可以使用dict.items()来遍历键和值对。

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