我一开始没有清楚地解释我的问题。
在将JSON转换为python中的字符串时,请尝试使用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.dumps()
用于将数据转换为 JSON 格式,而不是将 JSON 转换为字符串。 - Barmarstr
和 JSON 毫不相关;str(somedict)
看起来有点像 JSON 纯属巧合。str
是获取对象的字符串表现形式,可能与 JSON 完全不同(例如实现了__str__
方法的类)。 - Colonel Thirty Two