简体   繁体   中英

Read JSON-file in Python

I have a json file structured like this:

[ {"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"},

...

and I would like to read all IDs and all schemaIds for each entry in the json file. I am codin in 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. 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
  2. simple list comprehension
  3. data you will have been read from your file
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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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