简体   繁体   English

读取 Python 中的 JSON 文件

[英]Read JSON-file in Python

I have a json file structured like this:我有一个结构如下的 json 文件:

[ {"ID":"fjhgj","Label":{"objects":[{"featureId":"jhgd","schemaId":"hgkl","title":"Kuh","}],"classifications":[]},"Created By":"xxx_xxx","Project Name":"Tiererkennung"}, [ {"ID":"fjhgj","Label":{"objects":[{"featureId":"jhgd","schemaId":"hgkl","title":"Kuh","}],"分类":[]},"创建者":"xxx_xxx","项目名称":"Tiererkennung"},

{"ID":"jhgh","Label":{"objects":[{"featureId":"jhgd","schemaId":"erzl","title":"Kuh","}],"classifications":[]},"Created By":"xxx_xxx","Project Name":"Tiererkennung"}, {"ID":"jhgh","Label":{"objects":[{"featureId":"jhgd","schemaId":"erzl","title":"Kuh","}],"分类":[]},"创建者":"xxx_xxx","项目名称":"Tiererkennung"},

... ...

and I would like to read all IDs and all schemaIds for each entry in the json file.我想读取 json 文件中每个条目的所有 ID 和所有 schemaId。 I am codin in python.我是 python 的编码员。

What I tried is this:我尝试的是这样的:

import json
with open('Tierbilder.json') as f:
data=json.load(f)

data1 =data[0]
print(data1.values)

server_dict = {k:v for d in data for k,v in d.items()}
host_list = server_dict

Now I have the Problem that in host_list only the last row of my json file is saved.现在我遇到的问题是在 host_list 中只保存了我的 json 文件的最后一行。 How can I get another row, like the first one?我怎样才能得到另一行,就像第一行一样? Thanks for your help.谢谢你的帮助。

  1. structure your JSON so it's readable and structure is clear构建您的 JSON 使其可读且结构清晰
  2. simple list comprehension简单的列表理解
  3. data you will have been read from your file您将从文件中读取的data
data = [{'ID': 'fjhgj', 
         'Label': {'objects': [{'featureId': 'jhgd','schemaId': 'hgkl','title': 'Kuh'}], 'classifications': []},
         'Created By': 'xxx_xxx','Project Name': 'Tiererkennung'},
         {'ID': 'jhgh', 'Label': {'objects': [{'featureId': 'jhgd','schemaId': 'erzl','title': 'Kuh'}], 'classifications': []},
          'Created By': 'xxx_xxx','Project Name': 'Tiererkennung'}]

projschema = [{"ID":proj["ID"], "schemaId":schema["schemaId"]} 
              for proj in data 
              for schema in proj["Label"]["objects"]]

output output

[{'ID': 'fjhgj', 'schemaId': 'hgkl'}, {'ID': 'jhgh', 'schemaId': 'erzl'}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM