Sorry guys, I couldn't find the satisfying answer to print part of json response. Can someone help me here please:
import json
import requests
import pprint
response = requests.get('<api endpoing>')
json_data = response.json()
print(json.dumps(json_data, indent=4, sort_keys=True))
Json response would be
{
"Value1": "SomeValue",
"data": {
"subval1": false,
"subval2": "0a4",
"subval3": "",
"subval4": "Click h!",
"subval5": "1002",
"subval6": "932",
"subval7": "i2",
"subval8": 250,
"subval9": 0,
"subval10": 1,
"subval11": 3,
"subval12": 1,
"subval13": "<!>",
"subval14": "",
"subval15": "Click !!",
"subval16": "",
"subval17": 300
},
"error": true,
"message": "Success",
"status": 200
}
Now, I would like to traverse and print only the "data": values. I will do the following
data = json.loads(json_data)
data_set = (data['data'])
print(data_set)
But the error Im getting: TypeError: the JSON object must be str, not 'dict'
The Python "TypeError: the JSON object must be str, bytes or bytearray, not dict" occurs when we pass a dictionary to the json. loads() method. To solve the error, remove the call to json. loads() and use the json.
Use the json.loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary. This process is called deserialization – the act of converting a string to an object.
loads() method can be used to parse a valid JSON string and convert it into a Python Dictionary. It is mainly used for deserializing native string, byte, or byte array which consists of JSON data into Python Dictionary.
You don't need to json.loads(json_data)
as it is already a python dict, you just need to output this dict directly. And outputing json string from a dict is json.dumps()
's job :
json.dumps(json_data["data"])
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