Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

python - Accessing JSON elements

I am getting the weather information from a URL.

weather = urllib2.urlopen('url')
wjson = weather.read()

and what I am getting is:

{
  "data": {
     "current_condition": [{
        "cloudcover": "0",
        "humidity": "54",
        "observation_time": "08:49 AM",
        "precipMM": "0.0",
        "pressure": "1025",
        "temp_C": "10",
        "temp_F": "50",
        "visibility": "10",
        "weatherCode": "113",
        "weatherDesc": [{
            "value": "Sunny"
        }],
        "weatherIconUrl": [{
            "value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"
        }],
        "winddir16Point": "E",
        "winddirDegree": "100",
        "windspeedKmph": "22",
        "windspeedMiles": "14"
    }]        
 }
}

How can I access any element I want?

if I do: print wjson['data']['current_condition']['temp_C'] I am getting error saying:

string indices must be integers, not str.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
import json
weather = urllib2.urlopen('url')
wjson = weather.read()
wjdata = json.loads(wjson)
print wjdata['data']['current_condition'][0]['temp_C']

What you get from the url is a json string. And your can't parse it with index directly. You should convert it to a dict by json.loads and then you can parse it with index.

Instead of using .read() to intermediately save it to memory and then read it to json, allow json to load it directly from the file:

wjdata = json.load(urllib2.urlopen('url'))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...