首页 > 解决方案 > 如何从 json 值中抓取属性

问题描述

我试图通过一个看起来像这样的 json 来抓取一些值:

{
   "attributes":{
      "531":{
         "id":"531",
         "code":"taille",
         "label":"taille",
         "options":[
            {
               "id":"30",
               "label":"40",
               "is_in":"0"
            },
            {
               "id":"31",
               "label":"41",
               "is_in":"1"
            }
         ]
      }
   },
   "template":"Helloworld"
}

我的问题是,我试图抓取的每个 json 文件中的数字 531 都不同,而我试图通过这个 json 抓取的是标签is_in

到目前为止,我所做的是我试图做这样的事情,但我被卡住了,不知道如果 531 换成别的东西该怎么办

getOption = '{
       "attributes":{
          "531":{
             "id":"531",
             "code":"taille",
             "label":"taille",
             "options":[
                {
                   "id":"30",
                   "label":"40",
                   "is_in":"0"
                },
                {
                   "id":"31",
                   "label":"41",
                   "is_in":"1"
                }
             ]
          }
       },
       "template":"Helloworld"
    }'

for att, values in getOption.items():
    print(values)

那么我怎样才能刮取价值labelis_in

标签: pythonjsonfor-loop

解决方案


我不确定您是否可以拥有多个 531 键,但您可以遍历它们。

getOption = {
    "attributes":{
        "531":{
            "id":"531",
            "code":"taille",
            "label":"taille",
            "options":[
            {
                "id":"30",
                "label":"40",
                "is_in":"0"
            },
            {
                "id":"31",
                "label":"41",
                "is_in":"1"
            }
            ]
        }
    },
    "template":"Helloworld"
}

attributes = getOption['attributes']
for key in attributes.keys():
    for item in attributes[key]['options']:
        print(item['label'], item['is_in'])

推荐阅读