35

首先,我会坦率地承认,我只不过是一个笨拙的文科家伙,在这个脚本方面完全是自学成才的。也就是说,我正在尝试使用以下代码从 USGS 水数据服务中获取值:

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 响应中提取所需值的教程,但大多数都相当简单。我遇到的困难是从该服务返回的看起来非常复杂的响应中提取。查看响应,我可以看到我想要的是来自两个不同部分的值和一个时间值。因此,我可以查看响应并查看我需要什么,但我终其一生都无法弄清楚如何提取这些值。

4

5 回答 5

74

usingjson.loads会将您的数据转换为 python字典

使用字典值访问['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
于 2012-10-08T19:35:45.960 回答
21

唯一的建议是访问您的resp_dictvia.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.
于 2015-08-17T20:49:44.493 回答
7

从 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'])
于 2016-02-19T16:27:49.017 回答
3

试试这个。在这里,我只从COVID API - JSON 数组中获取状态码。

import requests

r = requests.get('https://api.covid19india.org/data.json')

x=r.json()['statewise']

for i in x:
  print(i['statecode'])
于 2021-04-14T12:43:33.043 回答
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'
于 2021-06-11T15:29:51.220 回答