【问题标题】:converting JSON to string in Python在 Python 中将 JSON 转换为字符串
【发布时间】: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 中的单引号字符串无效。

标签: python json string


【解决方案1】:

json.dumps() 不仅仅是从 Python 对象中创建一个字符串,它总是会在@987654323 之后生成一个有效的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)

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

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

【讨论】:

【解决方案2】:

还有其他区别。例如,{'time': datetime.now()} 不能序列化为 JSON,但可以转换为字符串。您应该根据目的使用其中一种工具(即稍后将解码结果)。

【讨论】:

  • 其实我更感兴趣的是他们单引号和双引号的区别。
  • 那么 alecxe 已经回答了你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-24
  • 2020-11-25
  • 2011-04-20
  • 2013-02-04
  • 2020-04-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多