简体   繁体   中英

How to cut a json with python

My plan is to "clean" the json below (json n.1) in order to only keep the location value, the date and the PM25 value (json n.2). I would like to do this with Python language. Does anyone know how to do this? Many thanks for your support.

json n.1 (dict):

 'level': 'hyper-local',
 'date': '2020-12-14T15:00:00+00:00',
 'pollutants': {'NO2': {'description': 'Nitrogen dioxide',
   'concentration': {'mugm3': {'value': 22}},
   'aqi': {'elichens': {'value': 11.0,
     'category': 'Very Low Pollution',
     'color': '#6cef00'}}},
  'O3': {'description': 'Ozone',
   'concentration': {'mugm3': {'value': 27}},
   'aqi': {'elichens': {'value': 11.0,
     'category': 'Very Low Pollution',
     'color': '#6cef00'}}},
  'PM25': {'description': 'Fine particulate matter (< 2.5 µm)',
   'concentration': {'mugm3': {'value': 9}},
   'aqi': {'elichens': {'value': 15.0,
     'category': 'Very Low Pollution',
     'color': '#93f400'}}},
  'PM10': {'description': 'Fine particulate matter (< 10 µm)',
   'concentration': {'mugm3': {'value': 15}},
   'aqi': {'elichens': {'value': 15.0,
     'category': 'Very Low Pollution',
     'color': '#93f400'}}}},
 'global_aqi': {'elichens': {'value': 15.0,
   'dominant': 'PM25',
   'info': 'eLichens Air Quality Index (eAQI)',
   'category': 'Very Low Pollution',
   'color': '#93f400'}}}

My goal is to get something like this:

json n.2 (dict):

 'pollutants': {'PM25': {'concentration': {'mugm3': {'value': 9}}}}}}

I managed to extract the information I needed like this:

pprint(data)
data1=data['location']['latitude']
data2=data['location']['longitude']
data2=data['date']
data3=data['pollutants']['PM25']['aqi']

Output for data1: 5.7782350000000005 (float)
Output for data2: 45.204480000000004 (float)
Output for data3: '2020-12-14T15:00:00+00:00' (string)
Output for data4: 15.0 (float)

Now I am trying to merge data1, data2, data3 and data4 in a json file

I managed extracting the data I needed with this piece of code (d is my json n.1, which is a dict). I guess this is not the perfect solution, but it works:)

location,date,pm=d['location'],d['date'],d['pollutants']['PM25']['aqi']['elichens']['value']
dict1={'location':location}
dict2={'date':date}
dict3={'PM25':pm}
dict1.update(dict2)
dict1.update(dict3)
print(dict1)

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