首先,我会自由地承认,只不过是一个笨拙的文科家伙,他在这个脚本中完全是自学成才。也就是说,我试图使用以下代码从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]
虽然我已经找到了一些关于如何从JSON响应中提取所需值的教程,但大多数都非常简单。我遇到的困难是从这个服务正在返回的非常复杂的响应中提取。通过回答,我可以看到我想要的是两个不同部分的值和时间值。因此,我可以看看响应,看看我需要什么,我不能,为了我的生活,弄清楚如何提取这些值。
答案 0 :(得分:42)
使用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 diction
resp_dict = json.loads(resp_str)
resp_dict['name'] # "ns1:timeSeriesResponseType"
resp_dict['value']['queryInfo']['creationTime'] # 1349724919000
答案 1 :(得分:11)
只有建议是通过resp_dict
访问.get()
以获得更优雅的方法,如果数据不符合预期,这种方法会很好地降低。
resp_dict = json.loads(resp_str)
resp_dict.get('name') # will return None if 'name' doesn't exist
如果你愿意的话,你也可以添加一些逻辑来测试密钥。
if 'name' in resp_dict:
resp_dict['name']
else:
# do something else here.
答案 2 :(得分:2)
从JSON响应Python中提取单个值
试试这个
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'])
答案 3 :(得分:0)
试试这个。 在这里,我仅从 COVID API - JSON 数组中获取 statecode。
import requests
r = requests.get('https://api.covid19india.org/data.json')
x=r.json()['statewise']
for i in x:
print(i['statecode'])
答案 4 :(得分:0)
试试这个:
from functools import reduce
import re
def deep_get_imps(data, key: str):
split_keys = re.split("[\\[\\]]", key)
out_data = data
for split_key in split_keys:
if split_key == "":
return out_data
elif isinstance(out_data, dict):
out_data = out_data.get(split_key)
elif isinstance(out_data, list):
try:
sub = int(split_key)
except ValueError:
return None
else:
length = len(out_data)
out_data = out_data[sub] if -length <= sub < length else None
else:
return None
return out_data
def deep_get(dictionary, keys):
return reduce(deep_get_imps, keys.split("."), dictionary)
然后你可以像下面这样使用它:
res = {
"status": 200,
"info": {
"name": "Test",
"date": "2021-06-12"
},
"result": [{
"name": "test1",
"value": 2.5
}, {
"name": "test2",
"value": 1.9
},{
"name": "test1",
"value": 3.1
}]
}
>>> deep_get(res, "info")
{'name': 'Test', 'date': '2021-06-12'}
>>> deep_get(res, "info.date")
'2021-06-12'
>>> deep_get(res, "result")
[{'name': 'test1', 'value': 2.5}, {'name': 'test2', 'value': 1.9}, {'name': 'test1', 'value': 3.1}]
>>> deep_get(res, "result[2]")
{'name': 'test1', 'value': 3.1}
>>> deep_get(res, "result[-1]")
{'name': 'test1', 'value': 3.1}
>>> deep_get(res, "result[2].name")
'test1'