35

まず第一に、私はこのスクリプトのことを完全に独学している不器用なリベラル アーツの男に過ぎないことを率直に認めます。とはいえ、以下のコードを使用して USGS Water Data Service から値を取得しようとしています。

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 応答から目的の値を抽出する方法に関するチュートリアルをいくつか見つけましたが、ほとんどはかなり単純です。私が抱えている問題は、このサービスが返す非常に複雑な応答のように見えるものから抽出することです。応答を見ると、2 つの異なるセクションからの値と時間の値が必要であることがわかります。したがって、私は応答を見て必要なものを確認できますが、私の人生では、これらの値を抽出する方法を理解することはできません.

4

5 に答える 5

74

を使用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
}

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 に答える