在python中将json转换为字符串

时间:2016-01-04 21:16:35

标签: python json string

我一开始并没有清楚地解释我的问题。 在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'&# 39;}"

>>> 
>>> 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"\'}'

我的预期输出:&#34; {&#39; jsonKey&#39;:&#39; jsonValue&#39;&#39; title&#39;:&#39; hello world \&#34; &#39;}&#34;

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

怎么做?感谢。

2 个答案:

答案 0 :(得分:80)

json.dumps()不仅仅是用Python对象创建一个字符串,它总是产生一个有效的JSON字符串(假设对象内的所有内容都是可序列化的)遵循Type Conversion Table

例如,如果其中一个值为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)

但是dumps()会将None转换为null,从而生成可以加载的有效JSON字符串:

>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}

答案 1 :(得分:1)

还有其他差异。例如,{'time': datetime.now()}无法序列化为JSON,但可以转换为字符串。您应该根据目的使用这些工具之一(即稍后将解码结果)。