Python-打印JSON对象的所有值

时间:2018-10-25 18:51:52

标签: python json

我有一个看起来像这样的JSON文件:

{
"authors": [
{
  "name": "John Steinbeck",
  "description": "An author from Salinas California"
},
{
  "name": "Mark Twain",
  "description": "An icon of american literature",
  "publications": [
    {
      "book": "Huckleberry Fin"
    },
    {
      "book": "The Mysterious Stranger"
    },
    {
      "book": "Puddinhead Wilson"
    }
  ]
},
{
  "name": "Herman Melville",
  "description": "Wrote about a famous whale.",
  "publications": [
    {
      "book": "Moby Dick"
    }
  ]
},
{
  "name": "Edgar Poe",
  "description": "Middle Name was Alan"
}
]
}

我正在使用python获取出版物元素的值。

我的代码如下:

import json
with open('derp.json') as f:
    data = json.load(f)
for i in range (0, len (data['authors'])):
    print data['authors'][i]['name']+data['authors'][i]['publications']

如果我只使用一个,我就能获得所有名称:

print data['authors'][i]['name']

但是当我尝试遍历以返回出版物时,出现了keyError。我希望这是因为Publications元素不是每个作者的一部分。

如何获取这些值以返回?

2 个答案:

答案 0 :(得分:0)

您可以做

if 'publications' in data['authors'][i].keys()

提前检查发布密钥是否存在

答案 1 :(得分:0)

您可以通过以下方式进行检查

 if 'publications' in (data['authors'][i])