Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON object must be str, bytes or bytearray, not dict

In Python 3, to load json previously saved like this:

json.dumps(dictionary)

the output is something like

{"('Hello',)": 6, "('Hi',)": 5}

when I use

json.loads({"('Hello',)": 6, "('Hi',)": 5})

it doesn't work, this happens:

TypeError: the JSON object must be str, bytes or bytearray, not 'dict' 
like image 435
dila93 Avatar asked Feb 20 '17 20:02

dila93


People also ask

What is the difference between JSON dump and JSON dumps?

json. dump() method used to write Python serialized object as JSON formatted data into a file. json. dumps() method is used to encodes any Python object into JSON formatted String.

What is JSON load?

load() json. load() takes a file object and returns the json object. It is used to read JSON encoded data from a file and convert it into a Python dictionary and deserialize a file itself i.e. it accepts a file object.


2 Answers

json.loads take a string as input and returns a dictionary as output.

json.dumps take a dictionary as input and returns a string as output.


With json.loads({"('Hello',)": 6, "('Hi',)": 5}),

You are calling json.loads with a dictionary as input.

You can fix it as follows (though I'm not quite sure what's the point of that):

d1 = {"('Hello',)": 6, "('Hi',)": 5} s1 = json.dumps(d1) d2 = json.loads(s1) 
like image 116
barak manos Avatar answered Sep 30 '22 04:09

barak manos


import json data = json.load(open('/Users/laxmanjeergal/Desktop/json.json')) jtopy=json.dumps(data) #json.dumps take a dictionary as input and returns a string as output. dict_json=json.loads(jtopy) # json.loads take a string as input and returns a dictionary as output. print(dict_json["shipments"]) 
like image 44
Laxman Jeergal Avatar answered Sep 30 '22 05:09

Laxman Jeergal