用python打印嵌套在数组中的json对象

4 人关注

我正在处理一个JSON文件,并且正在使用Python。我正试图打印一个嵌套在数组中的对象。我想打印以下数组中的选择对象(例如:"姓名"、"thomas_id")(它被认为是数组中 "对象 "的 "列表 "吗? 该数组是否被称为 the "共同赞助者 "阵列?)。

"cosponsors": [
  "district": null, 
  "name": "Akaka, Daniel K.", 
  "sponsored_at": "2011-01-25", 
  "state": "HI", 
  "thomas_id": "00007", 
  "title": "Sen", 
  "withdrawn_at": null
  "district": null, 
  "name": "Lautenberg, Frank R.", 
  "sponsored_at": "2011-01-25", 
  "state": "NJ", 
  "thomas_id": "01381", 
  "title": "Sen", 
  "withdrawn_at": null

问题是我不知道打印数组中的对象(列出的)的语法。我已经尝试了一些变化,这些变化是从我在stack overflow上发现的,即以下的变化。

print(data['cosponsors']['0']['thomas_id']

I recieve the error "list indices must be integers or slices, not str"

我有3000多个json文件,包含在一个所谓的主文件中。我只需要每个文件中相同的特定方面,以后我需要将其导出到MYSQL数据库中,但这是另一个话题(或者说是,我是不是走错了路?)因此,我正在写一个代码,我可以在所有的文件上实施,以获得我需要的数据。考虑到我没有任何编程经验,我已经做得相当好了。我一直在使用Python中的以下代码。

import json
data = json.load(open('s2_data.json', 'r'))
print (data["official_title"], data["number"], data["introduced_at"], 
data["bill_id"], data['subjects_top_term'], data['subjects'], 
data['summary']['text'], data['sponsor']['thomas_id'], 
data['sponsor']['state'], data['sponsor']['name'],  data['sponsor'] 
['type'])

它一直在返回用空格分隔的结果。到目前为止,我对这一点感到满意。

1 个评论
print(data['cosponsors'][0]['thomas_id'] - note 0, not "0"
python
arrays
json
Collective Action
Collective Action
发布于 2015-12-10
2 个回答
Martijn Pieters
Martijn Pieters
发布于 2015-12-10
已采纳
0 人赞同

你是用字符串来索引列表, '0' 是一个字符串,不是一个整数。去掉引号。

print(data['cosponsors'][0]['thomas_id'])

When in doubt, check the 部分结果;看看print(type(data['cosponsors']))产生什么。如果产生了<type 'list'>,你就知道你需要使用整数索引,如果你得到<type 'dict'>,就使用键(可以通过调用字典上的print(list(...))得到一个列表),等等。

通常,列表包含数量不等的对象;可能只有一个,也可能是零,或者是一大堆。你可以loop over those objects:

for cosponsor in data['cosponsors']:
    print(cosponsor['thomas_id'])

循环将cosponsor逐一设置给data['cosponsors']列表中的每个对象。

dnit13
dnit13
发布于 2015-12-10
0 人赞同