python解析json-fi

2024-03-28 22:14:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我不熟悉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

Tags: 文件代码namecomjsondatavaluelink
1条回答
网友
1楼 · 发布于 2024-03-28 22:14:37
  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'])

相关问题 更多 >