Python中如何提取JSON数据并处理常见问题
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 类型才能正常输出。请问大牛们这个问题得怎么解决,感激不尽。
Python中如何提取JSON数据并处理常见问题
已经解决,感谢。
要提取JSON数据,直接用json.loads()解析字符串,或者用json.load()读取文件。处理常见问题的话,主要注意编码、异常处理和数据类型转换。
比如解析字符串:
import json
json_str = '{"name": "张三", "age": 25, "city": "北京"}'
data = json.loads(json_str)
print(data['name']) # 输出:张三
读取JSON文件:
import json
with open('data.json', 'r', encoding='utf-8') as f:
data = json.load(f)
常见问题处理:
- 编码问题:确保文件用
utf-8编码打开 - 格式错误:用try-except捕获JSON解析错误
try:
data = json.loads(json_str)
except json.JSONDecodeError as e:
print(f"JSON解析错误: {e}")
- 处理嵌套数据:用
.操作符或循环遍历
# 假设data = {"user": {"profile": {"name": "李四"}}}
name = data['user']['profile']['name']
- 处理缺失键:用
.get()方法避免KeyError
value = data.get('key', '默认值')
如果JSON里有特殊类型(如日期),需要额外处理。用json.loads()的object_hook参数可以自定义解码逻辑。
总结:用标准库的json模块,注意编码和异常处理。
不写出怎么解决的?
对,怎么不写出怎么解决的?
message\ 这个就有问题了吧
<br>import json<br><br>with open('D:/data/py/data/3.json') as f:<br> src = f.readline()<br> s = src.decode('string-escape').strip('"')<br> d = json.loads(src)<br><br>print s<br>print type(d)<br>
数据被转义了。
* https://stackoverflow.com/questions/22600128/json-loads-is-returning-a-unicode-object-instead-of-a-dictionary
b = json.loads(a) 后发现 b 被存为 unicode 类型 需要转成 dict 类型才能读取出来,这里遇到困难了,怀疑是我的 json 格式不对 导致识别不了 dict
最后放弃了这个方法。
后面我是用 json 保存为 txt 用 re.findall 取我要的字符串。
null 跟 true 都不是 python 对象啊,怎么 loads 出来?,我很疑惑
这个我理解错了,我以为 json 当中的值只能是字符串,其实也可以是 ture,false,null
发现 json.loads 后 null 变成了 None


