在python中将json转换为字符串 [英] converting json to string in python

查看:199
本文介绍了在python中将json转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一开始并没有清楚地解释我的问题. 在python中将json转换为字符串时,尝试使用str()json.dumps().

I did not explain my questions clearly at beginning. Try to use str() and json.dumps() when converting json to string in python.

>>> 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).

It is not necessary to change the output string to json (dict) again for me.

该怎么做?

推荐答案

json.dumps() 不仅仅是从Python对象中生成字符串,它还会始终产生有效的例如,如果值之一是None,则str()会生成一个无法加载的无效JSON:

For instance, if one of the values is None, the str() would produce an invalid JSON which cannot be loaded:

>>> 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字符串:

But the dumps() would convert None into null making a valid JSON string that can be loaded:

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

这篇关于在python中将json转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆