Python 3.6.X JSON 转 str 无效无错

2017-11-14 15:32:20 +08:00
 SP00F
import json
a = '{"t": 1, "c": "a"}'
a = json.loads(a)
print(a["t"])

这样对字符串转 dict 是正常的。

但是如果

import json
a = "{'t': 1, 'c': 'a'}"
a = json.loads(a)

会报json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

import json
a = "{'t': 1, 'c': 'a'}"
a = json.dumps(a)
a = json.loads(a)
print(a["t"])

在进行loads()的时候没有报错,但是在调用的时候报TypeError: string indices must be integers

看了一圈资料有点懵,JSON 是不允许用单引号括起 key 的,Python 的 JSON 模块可以dumps转一下再loads但是就有点没理解了

2301 次点击
所在节点    Python
15 条回复
goofool
2017-11-14 15:41:18 +08:00
dumps 出去是字符串
loads 回来还是字符串
SP00F
2017-11-14 15:44:49 +08:00
@goofool #1
对单引号的字符串转 dict 用 dumps 再 loads 一下是不对的吗?
fasling
2017-11-14 15:47:00 +08:00
a = "{'t': 1, 'c': 'a'}"
这里的 a 并不是一个 json 串。json 得是双引号。你第二段的 json.dumps 和 json.loads 写了没有任何作用。
pixstone
2017-11-14 15:47:04 +08:00
```python
>>> import json
>>> a = "{'t': 1, 'c': 'a'}"
>>> a = json.dumps(a)
>>> a
'"{\'t\': 1, \'c\': \'a\'}"'
>>>
>>> a = json.loads(a)
>>> a
"{'t': 1, 'c': 'a'}"
>>>
```
goofool
2017-11-14 15:47:38 +08:00
@SP00F dumps 出去是个整体的字符串,单引号还是单引号,loads 回来还是不认单引号
pixstone
2017-11-14 15:48:46 +08:00
a = "{'t': 1, 'c': 'a'}" 是 str 不是 dict
所以你一顿操作后,还是 str

dict 应该写成
a = {'t': 1, 'c': 'a'}
SP00F
2017-11-14 15:50:22 +08:00
@fasling
@pixstone
@goofool

多谢各位,一直误以为 dumps 可以处理单引号的问题。
SP00F
2017-11-14 15:50:52 +08:00
@pixstone #6 dict 是这样写没错。。我是要把 str 转 dict。。。
soulomoon
2017-11-14 15:53:08 +08:00
看下报错不就好了吗。。。
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line:
这个是人家 json loader 不认单引号作为属性。

TypeError: string indices must be integers:
这个是你用 a["t"]引用的报错,他说你的 a 是个字符串.
SP00F
2017-11-14 15:54:15 +08:00
@soulomoon #9 是的。。就是我以为 dumps 可以解决单引号的问题。。。
fy
2017-11-14 16:03:10 +08:00
呃 你那个单引号的字符串,不是 JSON 格式。所以不存在 json 转 dict 的问题。
wuqiangroy
2017-11-14 16:58:08 +08:00
双引号直接用 eval(a)就可以了。
json 不能对 loads 双引号。
你 dumps 前是 str,loads 之后也是 str。
est
2017-11-14 17:11:23 +08:00
ast.literal_eval 通杀单引号双引号 u'' 引号
testcount
2017-11-14 17:54:59 +08:00
如果没有特别极致的性能要求,看到个 demjson 好像还不错。

mingyun
2017-11-18 18:58:50 +08:00
@testcount 这个库可以的

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/406307

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX