2014-10-08 35 views
0

我想從json源獲取溫度。它的嵌套,我無法弄清楚如何從一個JSON文件或URL嵌套值 所以這纔是我到目前爲止的代碼:如何提取嵌套json源中的值?

#! /usr/bin/python 
    import urllib2 
    import json 
    f = urllib2.urlopen('http://api.openweathermap.org/data/2.5/find?q=London&units=metric') 
    json_string = f.read() 
    parsed_json = json.loads(json_string) 
    temp = parsed_json['list'] 
    print "Current temperature is: %s" % (temp) 
    f.close() 

現在我可以一次獲得所有的值,但不只是一個特定的值(在我的情況下,溫度) 我更喜歡在沒有u'temp'的情況下獲取值:如果可能的話。

+1

優秀@ b4hand 這解決了我的情況好和容易。我實際上正在爲此奮鬥幾個小時:-) – ksp 2014-10-08 23:08:00

+0

如果只有某種[客觀的方式來表示讚賞](http://stackoverflow.com/help/accepted-answer)的答案。 – b4hand 2014-11-11 08:47:22

回答

0

u'temp'是Python如何表示unicode對象,這是JSON字符串在Python中解析到的對象。這是你在找什麼?

print temp[0]['main']['temp'] 

我不知道我們在調用API的結構,所以這可能使相當多的假設,但它可以把你的原始溫度。

0

您正在獲取多個值。要列出他們都這樣做:

import urllib2 
import json 

f = urllib2.urlopen('http://api.openweathermap.org/data/2.5/find?q=London&units=metric') 
json_string = f.read() 
parsed_json = json.loads(json_string) 
for each in parsed_json['list']: 
    country = each['sys']['country'] 
    temperature = each['main']['temp'] 
    print "Current Temperature in {} is {}".format(country, temperature) 

輸出

Current Temperature in CA is 11.73 
Current Temperature in GB is 11.8