107

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?

Syscall
  • 19,327
  • 10
  • 37
  • 52
BAE
  • 8,550
  • 22
  • 88
  • 171
  • The second form is not JSON, essentially. –  Jan 04 '16 at 21:18
  • There is a big difference when you have single vs double quotes, try loading with json.loads using the str version – Padraic Cunningham Jan 04 '16 at 21:18
  • `json.dumps()` is for converting **to** JSON, not from JSON to string. – Barmar Jan 04 '16 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__`). – Colonel Thirty Two Jan 04 '16 at 21:45
  • @ColonelThirtyTwo I know, In fact, I am more interested in their difference in single quote and double quote in output strings when the input are jsons. – BAE Jan 04 '16 at 21:48
  • 3
    @BAE JSON requires double-quote strings. Single-quoted strings in JSON are invalid. – Colonel Thirty Two Jan 04 '16 at 21:50

2 Answers2

177

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}
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • In fact, I am more interested in their difference in single quote and double quote in the output string. – BAE Jan 04 '16 at 21:31
  • 1
    @BAE well, in this case it is simple: http://stackoverflow.com/questions/4162642/python-single-vs-double-quotes-in-json. – alecxe Jan 04 '16 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).

Eugene Primako
  • 2,767
  • 9
  • 26
  • 35