111

I did not explain my questions clearly at beginning. Try to use str() and json.dumps() when converting JSON to string in python.

>>> data = {'jsonKey': 'jsonValue',"title": "hello world"}
>>> print json.dumps(data)
{"jsonKey": "jsonValue", "title": "hello world"}
>>> print str(data)
{'jsonKey': 'jsonValue', 'title': 'hello world'}
>>> json.dumps(data)
'{"jsonKey": "jsonValue", "title": "hello world"}'
>>> str(data)
"{'jsonKey': 'jsonValue', 'title': 'hello world'}"

My question is:

>>> data = {'jsonKey': 'jsonValue',"title": "hello world'"}
>>> str(data)
'{\'jsonKey\': \'jsonValue\', \'title\': "hello world\'"}'
>>> json.dumps(data)
'{"jsonKey": "jsonValue", "title": "hello world\'"}'
>>> 

My expected output: "{'jsonKey': 'jsonValue','title': 'hello world''}"

>>> data = {'jsonKey': 'jsonValue',"title": "hello world""}
  File "<stdin>", line 1
    data = {'jsonKey': 'jsonValue',"title": "hello world""}
                                                          ^
SyntaxError: EOL while scanning string literal
>>> data = {'jsonKey': 'jsonValue',"title": "hello world\""}
>>> json.dumps(data)
'{"jsonKey": "jsonValue", "title": "hello world\\""}'
>>> str(data)
'{\'jsonKey\': \'jsonValue\', \'title\': \'hello world"\'}'

My expected output: "{'jsonKey': 'jsonValue','title': 'hello world\"'}"

It is not necessary to change the output string to json (dict) again for me.

How to do this?

6
  • The second form is not JSON, essentially.
    – user948581
    Jan 4, 2016 at 21:18
  • There is a big difference when you have single vs double quotes, try loading with json.loads using the str version Jan 4, 2016 at 21:18
  • json.dumps() is for converting to JSON, not from JSON to string.
    – Barmar
    Jan 4, 2016 at 21:23
  • 3
    str has absolutely nothing to do with JSON; the fact that str(somedict) looks sort of like JSON is coincidence. str gets a string representation of an object, which may look nothing like JSON (ex. for classes that implement __str__). Jan 4, 2016 at 21:45
  • 3
    @BAE JSON requires double-quote strings. Single-quoted strings in JSON are invalid. Jan 4, 2016 at 21:50

2 Answers 2

184

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}
2
  • In fact, I am more interested in their difference in single quote and double quote in the output string.
    – BAE
    Jan 4, 2016 at 21:31
  • 1
    @BAE well, in this case it is simple: stackoverflow.com/questions/4162642/….
    – alecxe
    Jan 4, 2016 at 21:31
1

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).

2
  • In fact, I am more interested in their difference in single quotes and double quotes.
    – BAE
    Jan 4, 2016 at 21:31
  • Then alecxe has answered you. Jan 4, 2016 at 21:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.