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

knu*_*2xs 19 python json

首先,我会自由地承认,只不过是一个笨拙的文科家伙,他在这个脚本编写的东西中完全是自学成才.也就是说,我试图使用以下代码从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]
Run Code Online (Sandbox Code Playgroud)

虽然我找到了一些关于如何从JSON响应中提取所需值的教程,但大多数都非常简单.我遇到的困难是从这个服务正在返回的非常复杂的响应中提取.通过回答,我可以看到我想要的是两个不同部分的值和时间值.因此,我可以看看响应,看看我需要什么,我不能,为了我的生活,弄清楚如何提取这些值.

dm0*_*514 46

使用json.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
}
Run Code Online (Sandbox Code Playgroud)

会翻译成蟒蛇词

resp_dict = json.loads(resp_str)

resp_dict['name'] # "ns1:timeSeriesResponseType"

resp_dict['value']['queryInfo']['creationTime'] # 1349724919000
Run Code Online (Sandbox Code Playgroud)


But*_*rsB 13

唯一的建议是访问您的resp_dictvia .get()以获得更优雅的方法,如果数据不符合预期,这种方法会很好地降级.

resp_dict = json.loads(resp_str)
resp_dict.get('name') # will return None if 'name' doesn't exist
Run Code Online (Sandbox Code Playgroud)

如果你想要的话,你也可以添加一些逻辑来测试密钥.

if 'name' in resp_dict:
    resp_dict['name']
else:
    # do something else here.
Run Code Online (Sandbox Code Playgroud)


Sir*_*dda 6

从 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'])
Run Code Online (Sandbox Code Playgroud)


小智 6

尝试这个。

在这里,我仅从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'])
Run Code Online (Sandbox Code Playgroud)