将json字符串转储为unicode并解析回

时间:2019-08-27 11:59:32

标签: json python-2.7

我正在尝试将包含json的unicode字符串转储为另一个JSON的值,将其作为json响应传递给API并解析回去。它看起来非常琐碎,但我坚持使用它。

这是要复制的简化代码。

>>> s = {u'k': '123213'}
>>> d = {1: unicode(s)}
>>> d
{1: u"{u'k': '123213'}"}
>>> d[1]
u"{u'k': '123213'}"
>>> json.loads(d[1])

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 enclosed in double quotes: line 1 column 2 (char 1)

如何使用python 2.7将d[1]解析回有效的json?

1 个答案:

答案 0 :(得分:1)

使用ast模块

例如:

>>> s = {u'k': '123213'}
>>> d = {1: unicode(s)}
>>> import ast
>>> ast.literal_eval(d[1])
{u'k': '123213'}