Python 2.7 如何提取嵌套json源中的值?

Python 2.7 如何提取嵌套json源中的值?,python-2.7,Python 2.7,我试图从json源获取温度。它是嵌套的,我不知道如何从json文件或url获取嵌套值 到目前为止,我的代码如下: #! /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_js

我试图从json源获取温度。它是嵌套的,我不知道如何从json文件或url获取嵌套值 到目前为止,我的代码如下:

    #! /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()
现在我可以一次得到所有的值,但不只是一个特定的值(在我的例子中是temp)
我更喜欢在没有u'temp的情况下得到干净的值:如果可能的话。

u'temp'
是Python表示
unicode
对象的方式,这是Python中JSON字符串被解析成的内容。这就是你要找的吗

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

我不知道您正在调用的API的结构,因此这可能需要做很多假设,但它将为您获取原始温度。

您将返回多个值。要列出它们,请执行以下操作:

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

出色的@B4手,轻松解决了我的案子。事实上,我已经为此挣扎了好几个小时:-)如果有一些答案就好了。