简体   繁体   中英

How to display specific parts of json?

Can someone help me with this python api calling program?

import json
from pprint import pprint
import requests
weather = requests.get('http://api.openweathermap.org/data/2.5/weather?    
q=London&APPID=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
pprint(weather.json())

wjson = weather.read()
wjdata = json.load(weather)
print (wjdata['temp_max'])

So with this piece of code I'm trying to get information from the weather api it prints it properly but when I want to select certain values only I get this error.

Traceback (most recent call last):
  File "gawwad.py", line 7, in <module>
    wjson = weather.read()
AttributeError: 'Response' object has no attribute 'read'

.json() is a built into requests JSON decoder, no need to parse JSON separately:

import requests

weather = requests.get('http://api.openweathermap.org/data/2.5/weather?q=London&APPID=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
wjdata = weather.json()
print (wjdata['temp_max'])

alecxe is correct with using the json library, if you want to know more about referencing specific values in a json object, look into pythons Dictionary data types. That is what json essentially converts them into.

https://docs.python.org/3/tutorial/datastructures.html#dictionaries

The link above will show you how to use them!! Dictionaries are 'key-value' data structures where keys are unique and must not be hashable, and values are any type.

python Dictionary quick example:

dict = {'keyA' : 'valueA', 'keyB': 'valueB'}
# To reference a value, use the key!
print(dict['keyA'])
# To add something
dict['keyC'] = 'valueC'
# now my dictionary looks like this
dict = {'keyA' : 'valueA', 'keyB': 'valueB', 'KeyC' : 'valueC'}

The print statement will output, 'valueA'

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