json.dumps() is much more than just making a string out of a Python object, it would always produce a valid JSON string (assuming everything inside the object is serializable) following the Type Conversion Table.
For instance, if one of the values is None, the str() would produce an invalid JSON which cannot be loaded:
>>> data = {'jsonKey': None}
>>> str(data)
"{'jsonKey': None}"
>>> json.loads(str(data))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)
But the dumps() would convert None into null making a valid JSON string that can be loaded:
>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}
Answer from alecxe on Stack Overflowjson.dumps() is much more than just making a string out of a Python object, it would always produce a valid JSON string (assuming everything inside the object is serializable) following the Type Conversion Table.
For instance, if one of the values is None, the str() would produce an invalid JSON which cannot be loaded:
>>> data = {'jsonKey': None}
>>> str(data)
"{'jsonKey': None}"
>>> json.loads(str(data))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)
But the dumps() would convert None into null making a valid JSON string that can be loaded:
>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}
There are other differences. For instance, {'time': datetime.now()} cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).
Convert string to JSON in Python? - Stack Overflow
Convert from string to json python.
Text still behaves as a string after converting it to json?
Writing a json object as a string
How to Read and Parse JSON files in Python
How to parse JSON with Python Pandas
How to Pretty Print JSON data in Python
Hello,
UPDATE:
The problem is that I need to change the convert the data from string type to JSON.
How I got to the respective string ?
I am writing out the data from a dict. (no, I cannot convert from dict to JSON due to the architecture of the code behind)
The dictionary has the following values in it:
('sid', 'something funny'), ('subtitle', 'Nothing yet'), ('date', 'Today'), ('weather': 'Hot')
Afterwards I do the following: (The data is required as a string)
for key in dicts:
data = data + key + ' : ' + result[key] + '\n'
Then I have to change from this
title: something funny
subtitle: Nothing yet
date: Today
weather: Hot
to this
{
'title': 'something funny',
'subtitle': 'Nothing yet',
'date': 'Today',
'weather': 'Hot',
}
So far I've tried some variation of the following (but with no luck):
json.dumps(data, separators=('\n', ': '), sort_keys=True)
Does anyone have an idea on how should I approach this?
Thanks in advance!
I'm making a get request to a website and it returns me a string that is written as json (essentially taking json and converting it to a string). I then convert that string into json but it seems it still behaves as a string when I try to change one of the values. It gives me this error: "TypeError: 'str' object does not support item assignment". Why?
Here is my code:
r = requests.get(link) # get request
data = json.loads(r.text) # turn response into json
data["body"]["snip"]["balance"] = int(new_balance) # go through the json and replace the value named "balance" and thats where it throws the error.
Also, the "balance" value is an integer by default so I'm not changing its type.
I have a script that dumps a json object into a .json file after execution. Normally I would use json.dumps(dictionary) to do this. However I have a cache memory restriction that throws a monkey wrench into my plans. If the dictionary gets too big, I run into problems. I was wondering if I could write a dictionary as a string and them open it back up as a json file. For example, would thing like this be a good idea?
with open('test.json', 'wb') as fw:
fw.write('{"a":"b"}')Of course, this is a very trivial example that i came up with. If anyone has a better idea pls show me