How to extract a single value from JSON response?

前端 未结 3 1859
我在风中等你
我在风中等你 2020-11-27 13:43

First off, I will freely concede to being little more than a clumsy liberal arts guy who is completely self taught in this scripting thing. That said, I am attempting to get

相关标签:
3条回答
  • 2020-11-27 14:02

    using json.loads will turn your data into a python dictionary.

    Dictionaries values are accessed using ['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
    }
    

    would translate into a python diction

    resp_dict = json.loads(resp_str)
    
    resp_dict['name'] # "ns1:timeSeriesResponseType"
    
    resp_dict['value']['queryInfo']['creationTime'] # 1349724919000
    
    0 讨论(0)
  • 2020-11-27 14:18

    Extract single value from JSON response Python

    Try this

    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'])
    
    0 讨论(0)
  • 2020-11-27 14:21

    Only suggestion is to access your resp_dict via .get() for a more graceful approach that will degrade well if the data isn't as expected.

    resp_dict = json.loads(resp_str)
    resp_dict.get('name') # will return None if 'name' doesn't exist
    

    You could also add some logic to test for the key if you want as well.

    if 'name' in resp_dict:
        resp_dict['name']
    else:
        # do something else here.
    
    0 讨论(0)
提交回复
热议问题