Python 如何从 JSON 响应中提取单个值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12788217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to extract a single value from JSON response?
提问by knu2xs
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:
首先,我会坦率地承认自己只不过是一个笨拙的文科家伙,他在脚本方面完全自学。也就是说,我正在尝试使用以下代码从 USGS 水数据服务获取值:
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]
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.
虽然我找到了一些关于如何从 JSON 响应中提取所需值的教程,但大多数都相当简单。我遇到的困难是从这个服务返回的看起来非常复杂的响应中提取出来。查看响应,我可以看到我想要的是来自两个不同部分的值和一个时间值。因此,我可以查看响应并查看我需要什么,但在我的一生中,我无法弄清楚如何提取这些值。
采纳答案by dm03514
using json.loadswill turn your data into a python dictionary.
usingjson.loads会将您的数据转换为 python字典。
Dictionaries values are accessed using ['key']
使用字典值访问 ['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
}
would translate into a python diction
将翻译成python字典
resp_dict = json.loads(resp_str)
resp_dict['name'] # "ns1:timeSeriesResponseType"
resp_dict['value']['queryInfo']['creationTime'] # 1349724919000
回答by ButtersB
Only suggestion is to access your resp_dictvia .get()for a more graceful approach that will degrade well if the data isn't as expected.
唯一的建议是访问您的resp_dict通孔.get()以获得更优雅的方法,如果数据不符合预期,该方法会很好地降级。
resp_dict = json.loads(resp_str)
resp_dict.get('name') # will return None if 'name' doesn't exist
You could also add some logic to test for the key if you want as well.
如果需要,您还可以添加一些逻辑来测试密钥。
if 'name' in resp_dict:
resp_dict['name']
else:
# do something else here.
回答by Sireesh Yarlagadda
Extract single value from JSON response Python
从 JSON 响应 Python 中提取单个值
Try this
尝试这个
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'])

