2012-10-08 50 views
12

首先,我会自由地承认自己不仅仅是一个笨拙的文科家伙,他完全自学这门脚本。这就是说,我试图使用下面的代码从美国地质勘探局水情数据服务中获取值:从JSON响应中提取单个值Python

def main(gaugeId): 

    # import modules 
    import urllib2, json 

    # create string 
    url = "http://waterservices.usgs.gov/nwis/iv/?format=json&sites=" + gaugeId + "&parameterCd=00060,00065" 

    # open connection to url 
    urlFile = urllib2.urlopen(url) 

    # load into local JSON list 
    jsonList = json.load(urlFile) 

    # extract and return 
    # how to get cfs, ft, and zulu time? 
    return [cfs, ft, time] 

虽然我已经找到关于如何从一个JSON响应中提取所需的值一些教程,大多数都是相当简单。我遇到的困难是从这个服务返回的非常复杂的响应中提取出来。仔细查看回复,我可以看到我想要的是两个不同部分的值和一个时间值。因此,我可以看看答案,看看我需要什么,但我不能在我的生活中找出如何提取这些值。

感谢您解决这个问题的任何和所有帮助!

+7

你可以给JSON的样本,你需要什么样的价值?或者我们可以使用'gaugeId'的值。 –

+0

有人要求查看JSON响应。我很抱歉没有包括在内。而不是发布整个事情(这是相当大的),只需按照此链接:http://waterservices.usgs.gov/nwis/iv/?format=json&sites=01646500¶meterCd=00060,00065。从我可以告诉,我正在寻找价值> timeSeries>变量>值>值 – knu2xs

回答

25

使用json.loads会将您的数据变成python dictionary

字典值是使用['key']

resp_str = { 
    "name" : "ns1:timeSeriesResponseType", 
    "declaredType" : "org.cuahsi.waterml.TimeSeriesResponseType", 
    "scope" : "javax.xml.bind.JAXBElement$GlobalScope", 
    "value" : { 
    "queryInfo" : { 
     "creationTime" : 1349724919000, 
     "queryURL" : "http://waterservices.usgs.gov/nwis/iv/", 
     "criteria" : { 
     "locationParam" : "[ALL:103232434]", 
     "variableParam" : "[00060, 00065]" 
     }, 
     "note" : [ { 
     "value" : "[ALL:103232434]", 
     "title" : "filter:sites" 
     }, { 
     "value" : "[mode=LATEST, modifiedSince=null]", 
     "title" : "filter:timeRange" 
     }, { 
     "value" : "sdas01", 
     "title" : "server" 
     } ] 
    } 
    }, 
    "nil" : false, 
    "globalScope" : true, 
    "typeSubstituted" : false 
} 

将转化为一个Python文辞

resp_dict = json.loads(resp_str) 

resp_dict['name'] # "ns1:timeSeriesResponseType" 

resp_dict['value']['queryInfo']['creationTime'] # 1349724919000 
4

唯一的建议是通过获得()来访问你的resp_dict一个更优雅的方式,将降低访问以及如果数据不符合预期。

resp_dict = json.loads(resp_str) 
resp_dict.get('name') # will return None if 'name' doesn't exist 

如果你想要的话,你也可以添加一些逻辑来测试关键。从JSON响应的Python

if 'name' in resp_dict: 
    resp.dict['name'] 
else: 
    # do something else here. 
1

提取单值试试这个

import json 
import sys 

#load the data into an element 
data={"test1" : "1", "test2" : "2", "test3" : "3"} 

#dumps the json object into an element 
json_str = json.dumps(data) 

#load the json to a string 
resp = json.loads(json_str) 

#print the resp 
print (resp) 

#extract an element in the response 
print (resp['test1'])