繁体   English   中英

用python解析嵌套的json

[英]Parsing nested json with python

提交请求后,我收到了以下json回信:

{"type": [
{"ID": "all", "count": 1, "references": [
    { "id": "Boston,MA,02118", "text": "Boston,MA,02118", "val": "Boston,MA,02118", "type": 1 ,"zip": "02118","city": "Boston","state": "MA","lt": "42.3369","lg": "-71.0637","s": ""}
] }
] } 

我在变量j中捕获了响应,

>>> j
'{"type": [\r\n\t{"ID": "all", "count": 1, "references": [\r\n\t\t{ "id": "Boston,MA,02118", "text": "Boston,MA,02118", "val": "Boston,MA,02118", "type": 1 ,"zip": "02118","city": "Boston","state": "MA","lt": "42.3369","lng": "-71.0637","s": ""}\r\n\t] }\r\n] }'

并试图解析它:

>>> j['types']
TypeError: string indices must be integers, not str      

我究竟做错了什么?

您已经有了字典的JSON字符串表示形式。 但是您正在尝试将该字符串用作字典。 那行不通; 您需要先使用json模块解析它:

import json
obj = json.loads(j)
obj['types']

(有些库可以包装整个“发送请求,获取响应,从响应中提取主体,确保内容类型适合JSON,对其进行解析,在出现任何错误时引发异常”)您。但是,如果您不使用它,则无法跳过任何步骤。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM