What is the difference between json.dumps(..) and str(..)?
Don't they both convert json to string?
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.
loads() takes in a string and returns a json object. json. dumps() takes in a json object and returns a string.
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.
json. dumps() function converts a Python object into a json string.
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.
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