【发布时间】:2016-04-08 14:07:03
【问题描述】:
一开始我没有清楚地解释我的问题。
在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'}"
我的问题是:
>>> data = {'jsonKey': 'jsonValue',"title": "hello world'"}
>>> str(data)
'{\'jsonKey\': \'jsonValue\', \'title\': "hello world\'"}'
>>> json.dumps(data)
'{"jsonKey": "jsonValue", "title": "hello world\'"}'
>>>
我的预期输出:"{'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"\'}'
我的预期输出:"{'jsonKey': 'jsonValue','title': 'hello world\"'}"
我不需要再把输出字符串改成json(dict)。
如何做到这一点?
【问题讨论】:
-
第二种形式本质上不是 JSON。
-
单引号和双引号有很大区别,尝试使用str版本加载json.loads
-
json.dumps()用于将 转换为 JSON,而不是从 JSON 转换为字符串。 -
str与 JSON完全无关;str(somedict)看起来有点像 JSON 的事实是巧合。str获取对象的字符串表示形式,它可能看起来不像 JSON(例如,对于实现__str__的类)。 -
@BAE JSON 需要双引号字符串。 JSON 中的单引号字符串无效。