Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between json.dumps and str()? [closed]

What is the difference between json.dumps(..) and str(..)?

Don't they both convert json to string?

like image 793
Phil Avatar asked Mar 03 '14 18:03

Phil


People also ask

What is the difference between JSON dumps and JSON dump?

The json. dump() method (without “s” in “dump”) used to write Python serialized object as JSON formatted data into a file. The json. dumps() method encodes any Python object into JSON formatted String.

What is the difference between JSON dumps and loads?

loads() takes in a string and returns a json object. json. dumps() takes in a json object and returns a string.

What is a JSON dumps?

The json. dumps() method allows us to convert a python object into an equivalent JSON object. Or in other words to send the data from python to json. The json. dump() method allows us to convert a python object into an equivalent JSON object and store the result into a JSON file at the working directory.

Does JSON dump string?

json. dumps() function converts a Python object into a json string.


1 Answers

No. In fact in (I believe most) implementations of Python, str(object) wraps strings in single quotes, which is not valid JSON.

An example:

In [17]: print str({"a": 1})
{'a': 1}

str(boolean) is also not valid JSON:

In [18]: print str(True)
True

__str__, can, however, be overridden in user defined classes to ensure that objects return JSON representations of themselves.

like image 95
Joel Cornett Avatar answered Sep 17 '22 21:09

Joel Cornett