如何从JSON响应中提取单个值? [英] How to extract a single value from JSON response?
问题描述
首先,我将自由地允许自己成为一个笨拙的文科专家,他完全可以自学此脚本.就是说,我正在尝试使用以下代码从USGS水数据服务获取值:
First off, I will freely concede to being little more than a clumsy liberal arts guy who is completely self taught in this scripting thing. That said, I am attempting to get values from a the USGS Water Data Service using the code below:
def main(gaugeId):
# import modules
import urllib2, json
# create string
url = "http://waterservices.usgs.gov/nwis/iv/?format=json&sites=" + gaugeId + "¶meterCd=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响应中提取所需值的教程,但大多数教程都非常简单.我遇到的困难是从该服务返回的看起来非常复杂的响应中提取出来的.查看响应,可以看到我想要的是来自两个不同部分的值和一个时间值.因此,我可以查看响应并查看我的需求,但我一生都无法弄清楚如何提取这些值.
Although I have found some tutorials regarding how to extract the desired values from a JSON response, most are fairly simple. The difficulty I am having is extracting from what looks like a very complicated response this service is returning. Looking through the response, I can see what I want is the value from two different sections and a time value. Hence, I can look at the response and see what I need, I just cannot, for the life of me, figure out how to get these values extracted.
推荐答案
using json.loads
will turn your data into a 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字典
would translate into a python diction
resp_dict = json.loads(resp_str)
resp_dict['name'] # "ns1:timeSeriesResponseType"
resp_dict['value']['queryInfo']['creationTime'] # 1349724919000
这篇关于如何从JSON响应中提取单个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!