【问题标题】:How to scrape attributes from json values如何从 json 值中抓取属性
【发布时间】:2019-07-23 18:03:25
【问题描述】:

我正在尝试通过如下所示的 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 抓取的是 labelis_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

【问题讨论】:

  • @Slai 对不起!是 Python
  • 有一个名为“Glom”的第三方库可能会有所帮助 - 它可以让您为任意 JSON 设置一个“目标”,这可能在这里有用!

标签: python json for-loop


【解决方案1】:

我不确定您是否可以拥有多个 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'])

【讨论】:

  • 很抱歉回复晚了,但这正是我想要的! :)
猜你喜欢
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-29
  • 1970-01-01
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
相关资源
最近更新 更多