首页 > 解决方案 > python解析json文件

问题描述

我是 python 和 json 的新手。我有一个下面的 json 文件,我需要在其中解析 json 文件中的“值”

{
  "link": [
    {
      "attributes": [
        {
          "value": "backup",
          "name": "name"
        },
        {
          "value": "",
          "name": "description"
        }
      ],

    },
    {
      "attributes": [
        {
          "value": "com.cap.blueprints",
          "name": "name"
        },
        {
          "value": "",
          "name": "description"
        }
      ],

    }
  ],
}

我试过下面的代码。但我收到错误

with open ("respose_json.txt") as f2:
 data=json.load(f2)
 for x in data:
  print(x['attributes']['value']) 

error:
    print(x['attributes']['value']) 
TypeError: string indices must be integers

标签: pythonjson

解决方案


  1. 您缺少最外层的link键。
  2. 属性包含属性列表,每个属性都有值。

尝试这样的事情:

import json

with open("respose_json.txt") as json_file:
    data = json.loads(json_file)["link"]

    for attributes in data:
        for attribute in attributes['attributes']:
            print(attribute['value'])

推荐阅读