To extract the scalar value from the JSON string, use the json_extract_scalar function. It is similar to json_extract , but returns only scalar values (Boolean, number, or string).
Converting JSON file to Python object Apart from JSON, Python's native open() function will also be required. Instead of the JSON loads method, which reads JSON strings, the method used to read JSON data in files is load(). The load() method takes up a file object and returns the JSON data parsed into a Python object.
JSON data, at its simplest, can be a single object composed of fields, with each field having a simple value. Some terminology: A value can be a simple value, an array, or an object. A simple value can be a string, a number, or a Boolean value true or false , or null .
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
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.
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'])
Try this. Here, I fetch only statecode from COVID API - JSON Array.
import requests
r = requests.get('https://api.covid19india.org/data.json')
x=r.json()['statewise']
for i in x:
print(i['statecode'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With