Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从JSON响应中提取单个值?_Python_Json - Fatal编程技术网

Python 如何从JSON响应中提取单个值?

Python 如何从JSON响应中提取单个值?,python,json,Python,Json,首先,我会毫不犹豫地承认自己只是一个笨拙的文科学生,在这个脚本编写方面完全自学成才。也就是说,我正试图使用以下代码从USGS水数据服务获取值: def main(gaugeId): # import modules import urllib2, json # create string url = "http://waterservices.usgs.gov/nwis/iv/?format=json&sites=" + gaugeId + "&

首先,我会毫不犹豫地承认自己只是一个笨拙的文科学生,在这个脚本编写方面完全自学成才。也就是说,我正试图使用以下代码从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响应中提取所需值的教程,但大多数都相当简单。我遇到的困难是从这个服务返回的看起来非常复杂的响应中提取。通过查看响应,我可以看到我想要的是来自两个不同部分的值和一个时间值。因此,我可以查看响应并了解我需要什么,但就我的一生而言,我无法找出如何提取这些值。

使用
json。加载将把数据转换为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

唯一的建议是通过
.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.

从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'])
试试这个。 在这里,我只从covidapi-JSON数组中获取状态码

import requests

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

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

for i in x:
  print(i['statecode'])
试试这个:

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)


您能给出json的一个示例以及您需要的值吗?或者我们可以使用的
gaugeId
的值。有人要求查看JSON响应。我很抱歉没有把它包括进去。不要发布整个内容(它相当大),只需遵循以下链接:。据我所知,我正在寻找value>timeSeries>variable>value>value我为导航使用了以下方法:
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'