在python中将json转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34600003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
converting json to string in python
提问by BAE
I did not explain my questions clearly at beginning.
Try to use str()
and json.dumps()
when converting json to string in python.
一开始我没有把我的问题解释清楚。尝试在 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'}"
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''}"
我的预期输出: "{'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\"'}"
我的预期输出: "{'jsonKey': 'jsonValue','title': 'hello world\"'}"
It is not necessary to change the output string to json (dict) again for me.
对于我来说,没有必要再次将输出字符串更改为 json (dict)。
How to do this?
这该怎么做?
采纳答案by alecxe
json.dumps()
is much more than just making a string out of a Python object, it would always produce a valid JSONstring(assuming everything inside the object is serializable) following the Type Conversion Table.
json.dumps()
不仅仅是从 Python 对象中生成一个字符串,它总是会在类型转换表之后生成一个有效的JSON字符串(假设对象内的所有内容都是可序列化的)。
For instance, if one of the values is None
, the str()
would produce an invalid JSON which cannot be loaded:
例如,如果其中一个值为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)
But the dumps()
would convert None
into null
making a valid JSON string that can be loaded:
但是dumps()
会转换None
为null
可以加载的有效 JSON 字符串:
>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}
回答by Eugene Primako
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).
还有其他区别。例如,{'time': datetime.now()}
不能序列化为 JSON,但可以转换为字符串。您应该根据目的使用这些工具之一(即稍后会解码结果)。