在python中将json转换为字符串

BAE*_*BAE 57 python string json

我没有在开始时清楚地解释我的问题.在python中将json转换为字符串时,尝试使用str()和json.dumps().

>>> 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'}"
Run Code Online (Sandbox Code Playgroud)

我的问题是:

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

我的预期输出:"{'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"\'}'
Run Code Online (Sandbox Code Playgroud)

我的预期输出:"{'jsonKey':'jsonValue','title':'hello world \''}"

PS:没有必要再次将输出字符串更改为json(dict).

这该怎么做?谢谢.

ale*_*cxe 99

json.dumps()不仅仅是从Python对象中创建一个字符串,它总是会在类型转换表之后生成一个有效的JSON字符串(假设对象内的所有内容都是可序列化的).

例如,如果其中一个值为None,str()则会产生无法加载的无效JSON:

>>> 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)
Run Code Online (Sandbox Code Playgroud)

但是dumps()转换Nonenull生成可以加载的有效JSON字符串:

>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}
Run Code Online (Sandbox Code Playgroud)