如何用python解析json文本数据

时间:2016-05-28 14:45:46

标签: python json

我需要向我的客户端的api发出请求,api会返回这些数据:

[6,0,'VT3zrYA',5,'USUeZWA',5,0,0,0,0,0,4,0,0,0,2,0,0,3,0,0,0,0,2,0,1,["portale.titolari.client.config.ShoulderDTO/4121330600","java.util.HashSet/3273092938","MATTEO SBRAGIA","java.util.ArrayList/4159755760","java.util.Date/3385151746","MATTEO"],0,7]

如何解析此数据并提取以下字段:

MATTEO SBRAGIA
MATTEO

我已尝试过此代码,但它无效:

data = json.load(output_data)
pprint data

1 个答案:

答案 0 :(得分:2)

这实际上不是有效的JSON字符串,因为它包含单引号'。你可以用双引号替换所有单引号,然后解析字符串,但这是一个有意或错误的问题:

import json

s = '[6,0,\'VT3zrYA\',5,\'USUeZWA\',5,0,0,0,0,0,4,0,0,0,2,0,0,3,0,0,0,0,2,0,1,["portale.titolari.client.config.ShoulderDTO/4121330600","java.util.HashSet/3273092938","MATTEO SBRAGIA","java.util.ArrayList/4159755760","java.util.Date/3385151746","MATTEO"],0,7]'

data = json.loads(s.replace("\'", '"'))

print(data[26][2])
print(data[26][5])

打印:

$ python test.py 
MATTEO SBRAGIA
MATTEO