请教关于 json 提取数据的问题

2017-08-10 02:25:58 +08:00
 jayjing
3.json
"{\"message\":null,\"result\":{\"data\":[{\"id\":\"1700519714\",\"type\":\"ADD\",\"keyWord\":\"999999\",\"userId\":\"604B868F7C39427AAB651BF2234DE5A6\",\"createTm\":\"2017/07/24\",\"sourceCode\":\"ODR\",\"thisPoint\":\"90\",\"detailDesc\":\"test\",\"curTotalPoint\":\"597\"}],\"totalCount\":1,\"pageSize\":5,\"pageNo\":1,\"totalPage\":1,\"curPoint\":597},\"status\":\"1\",\"success\":true,\"errorcode\":null}"

需要提取 keyWord 999999

import json
f = open('C:/3.json')
a = f.readline()
b = json.loads(a)
d = b['message\\']
print d
f.close()

运行发现
C:\Users\Administrator\Desktop>C:\Users\Administrator\Desktop\json\1\test.py
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\json\1\test.py", line 5, in <module>
d = b['message\\']
TypeError: string indices must be integers

一步一步排查发现 b 为<type 'unicode'>类型 是不是 b 应该为 dict 类型才能正常输出。请问大牛们这个问题得怎么解决,感激不尽。
2373 次点击
所在节点    Python
10 条回复
jayjing
2017-08-10 03:45:08 +08:00
已经解决,感谢。
anyele
2017-08-10 07:54:24 +08:00
@jayjing 不写出怎么解决的?
957204459
2017-08-10 09:15:45 +08:00
对,怎么不写出怎么解决的?
hand515
2017-08-10 09:19:29 +08:00
message\\ 这个就有问题了吧
mxmai
2017-08-10 09:25:07 +08:00
```
import json

with open('D:/data/py/data/3.json') as f:
src = f.readline()
s = src.decode('string-escape').strip('"')
d = json.loads(src)

print s
print type(d)
```
数据被转义了。

* https://stackoverflow.com/questions/22600128/json-loads-is-returning-a-unicode-object-instead-of-a-dictionary
jayjing
2017-08-10 11:11:15 +08:00
b = json.loads(a) 后发现 b 被存为 unicode 类型 需要转成 dict 类型才能读取出来,这里遇到困难了,怀疑是我的 json 格式不对 导致识别不了 dict
最后放弃了这个方法。
后面我是用 json 保存为 txt 用 re.findall 取我要的字符串。
strict
2017-08-10 11:55:05 +08:00
null 跟 true 都不是 python 对象啊,怎么 loads 出来?,我很疑惑
hellove1985
2017-08-10 11:59:46 +08:00
@strict 这两个有什么关系,为什么不能 loads 出来?,我很疑惑
strict
2017-08-10 13:22:37 +08:00
@hellove1985 这个我理解错了,我以为 json 当中的值只能是字符串,其实也可以是 ture,false,null
mingyun
2017-08-10 23:14:40 +08:00
发现 json.loads 后 null 变成了 None

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

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

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

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

© 2021 V2EX