Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: the JSON object must be str, not 'dict'

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'

like image 504
Manoj Kengudelu Avatar asked Mar 20 '17 09:03

Manoj Kengudelu


People also ask

How do I fix TypeError the JSON object must be str bytes or Bytearray 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.

How do you convert a string to a JSON object in Python?

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.

What is JSON loads in Python?

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.


1 Answers

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"])
like image 148
n00dl3 Avatar answered Sep 20 '22 18:09

n00dl3