循环通过JSON列表

时间:2017-06-19 00:22:49

标签: python json parsing

我正在将JSON数组导入python,我想知道是什么触发了我的错误。我在这种情况下使用冰淇淋的例子。

我的JSON有多个用例:

{
  "cones": 1,
  "toppings": [
    {
      "chocolate_chips": "yes",
      "cherries": 1,
      "sprinkles": "rainbow"
    },
    {
      "chocolate_chips": "yes",
      "cherries": 3,
      "sprinkles": "chocolate"
    },
    {
      "chocolate_chips": "yes",
      "cherries": 2,
      "sprinkles": "rainbow"
    }
  ],
  "whipped_cream": [
    "lots",
    "some",
    "none"
  ]
}

{
  "cones": 1,
  "cherries": 3,
  "chocolate_chips": "Yes",
  "sprinkles": "chocolate",
  "whipped_cream": [
    "Lots",
    "Some",
    "None"
  ]
}

注意一个JSON如何有一个标题为toppings的列表,其中包含字段巧克力碎片,樱桃和洒水,而另一个JSON根本没有包含该列表,只包含值。我正在运行这个脚本试图分配无论如何都可以工作的变量,这是我的代码到目前为止。

ice_cream = json.loads(json)

for i in ice_cream:
    if ice_cream['toppings'] is not None:
        toppings = (i.get('toppings'))
        for t in toppings:
            chocolate_chips = (t.get('chocolate_chips'))
            cherries:(t.get('cherries'))
            sprinkles:(t.get('sprinkles'))
    else: 
        chocolate_chips = (i.get('chocolate_chips'))
        cherries:(i.get('cherries'))
        sprinkles:(i.get('sprinkles'))
    cones = (i.get('cones'))
    whipped_cream = (i.get('whipped_cream'))

我收到此错误

list indices must be integers, not str

0 个答案:

没有答案