【问题标题】:How to get values of keys for changing Json如何获取更改 Json 的键值
【发布时间】:2019-01-09 23:11:09
【问题描述】:

我正在使用python2.7

我有一个我拉的 json,当我请求它时它总是在变化。

我需要在我的字典中的 Relation6 下的 Term7 下拉出Animal_Target_DisplayName。

问题有时是对象 Relation6 位于 Json 的另一部分,它可能会更深层次或以其他顺序。

我正在尝试创建只能导出键 Animal_Target_DisplayName 的值的代码,但没有任何效果。它甚至不会循环嵌套的字典。

现在,如果我使用 ['view']['Term0'][0]['Relation6'] 之类的东西将其拉出,这可以工作,但请记住 JSON 永远不会以相同的结构返回。

我用来获取键 Animal_Target_DisplayName 的值的代码,但它似乎没有循环遍历我的字典并使用该键找到所有值。

array = []
for d in dict.values():
    row = d['Animal_Target_DisplayName']
    array.append(row)

JSON 下面:

dict = {  
   "view":{  
      "Term0":[  
         {  
            "Id":"b0987b91-af12-4fe3-a56f-152ac7a4d84d",
            "DisplayName":"Dog",
            "FullName":"Dog",
            "AssetType1":[  
               {  
                  "AssetType_Id":"00000000-0000-0000-0000-000000031131",
               }
            ]
         },
         {  
            "Id":"ee74a59d-fb74-4052-97ba-9752154f015d",
            "DisplayName":"Dog2",
            "FullName":"Dog",
            "AssetType1":[  
               {  
                  "AssetType_Id":"00000000-0000-0000-0000-000000031131",
               }
            ]
         },
         {  
            "Id":"eb548eae-da6f-41e8-80ea-7e9984f56af6",
            "DisplayName":"Dog3",
            "FullName":"Dog3",
            "AssetType1":[  
               {  
                  "AssetType_Id":"00000000-0000-0000-0000-000000031131",
               }
            ]
         },
         {  
            "Id":"cfac6dd4-0efa-4417-a2bf-0333204f8a42",
            "DisplayName":"Animal Set",
            "FullName":"Animal Set",
            "AssetType1":[  
               {  
                  "AssetType_Id":"00000000-0000-0000-0001-000400000001",
               }
            ],
            "StringAttribute2":[  
               {  
                  "StringAttribute_00000000-0000-0000-0000-000000003114_Id":"00a701a8-be4c-4b76-a6e5-3b0a4085bcc8",
                  "StringAttribute_00000000-0000-0000-0000-000000003114_Value":"Desc"
               }
            ],
            "StringAttribute3":[  
               {  
                  "StringAttribute_00000000-0000-0000-0000-000000000262_Id":"a81adfb4-7528-4673-8c95-953888f3b43a",
                  "StringAttribute_00000000-0000-0000-0000-000000000262_Value":"meow"
               }
            ],
            "BooleanAttribute4":[  
               {  
                  "BooleanAttribute_00000000-0000-0000-0001-000500000001_Id":"932c5f97-c03f-4a1a-a0c5-a518f5edef5e",
                  "BooleanAttribute_00000000-0000-0000-0001-000500000001_Value":"true"
               }
            ],
            "SingleValueListAttribute5":[  
               {  
                  "SingleValueListAttribute_00000000-0000-0000-0001-000500000031_Id":"ef51dedd-6f25-4408-99a6-5a6cfa13e198",
                  "SingleValueListAttribute_00000000-0000-0000-0001-000500000031_Value":"Blah"
               }
            ],
            "Relation6":[  
               {  
                  "Animal_Id":"2715ca09-3ced-4b74-a418-cef4a95dddf1",
                  "Term7":[  
                     {  
                        "Animal_Target_Id":"88fd0090-4ea8-4ae6-b7f0-1b13e5cf3d74",
                        "Animal_Target_DisplayName":"Animaltheater",
                        "Animal_Target_FullName":"Animaltheater"
                     }
                  ]
               },
               {  
                  "Animal_Id":"6068fe78-fc8e-4542-9aee-7b4b68760dcd",
                  "Term7":[  
                     {  
                        "Animal_Target_Id":"4e87a614-2a8b-46c0-90f3-8a0cf9bda66c",
                        "Animal_Target_DisplayName":"Animaltitle",
                        "Animal_Target_FullName":"Animaltitle"
                     }
                  ]
               },
               {  
                  "Animal_Id":"754ec0e6-19b6-4b6b-8ba1-573393268257",
                  "Term7":[  
                     {  
                        "Animal_Target_Id":"a8986ed5-3ec8-44f3-954c-71cacb280ace",
                        "Animal_Target_DisplayName":"Animalcustomer",
                        "Animal_Target_FullName":"Animalcustomer"
                     }
                  ]
               },
               {  
                  "Animal_Id":"86b3ffd1-4d54-4a98-b25b-369060651bd6",
                  "Term7":[  
                     {  
                        "Animal_Target_Id":"89d02067-ebe8-4b87-9a1f-a6a0bdd40ec4",
                        "Animal_Target_DisplayName":"Animalfact_transaction",
                        "Animal_Target_FullName":"Animalfact_transaction"
                     }
                  ]
               },
               {  
                  "Animal_Id":"ea2e1b76-f8bc-46d9-8ebc-44ffdd60f213",
                  "Term7":[  
                     {  
                        "Animal_Target_Id":"e398cd32-1e73-46bd-8b8f-d039986d6de0",
                        "Animal_Target_DisplayName":"Animalfact_transaction",
                        "Animal_Target_FullName":"Animalfact_transaction"
                     }
                  ]
               }
            ],
            "Relation10":[  
               {  
                  "TargetRelation_b8b178ff-e957-47db-a4e7-6e5b789d6f03_Id":"aff80bd0-a282-4cf5-bdcc-2bad35ddec1d",
                  "Term11":[  
                     {  
                        "AnimalId":"3ac22167-eb91-469a-9d94-315aa301f55a",
                        "AnimalDisplayName":"Animal",
                        "AnimalFullName":"Animal"
                     }
                  ]
               }
            ],
            "Tag12":[  
               {  
                  "Tag_Id":"75968ea6-4c9f-43c9-80f7-dfc41b24ec8f",
                  "Tag_Name":"AnimalAnimaltitle"
               },
               {  
                  "Tag_Id":"b1adbc00-aeef-415b-82b6-a3159145c60d",
                  "Tag_Name":"Animal2"
               },
               {  
                  "Tag_Id":"5f78e4dc-2b37-41e0-a0d3-cec773af2397",
                  "Tag_Name":"AnimalDisplayName"
               }
            ]
         }
      ]
   }
}

我试图得到的输出是来自键 Animal_Target_DisplayName 的所有值的列表,就像这个 ['Animaltheater','Animaltitle', 'Animalcustomer', 'Animalfact_transaction', 'Animalfact_transaction'] 但我们需要记住这个 json 的嵌套结构总是会改变,但它的键总是相同的。

【问题讨论】:

    标签: python json python-2.7


    【解决方案1】:

    我猜你唯一的选择是遍历整个 dict 并获取 Animal_Target_DisplayName 键的值,我提出以下递归解决方案:

    def run_json(dict_):
        animal_target_sons = []
        if type(dict_) is list:
            for element in dict_:
                animal_target_sons.append(run_json(element)) 
        elif type(dict_) is dict:
            for key in dict_:
                if key=="Animal_Target_DisplayName":
                    animal_target_sons.append([dict_[key]])
                else:
                    animal_target_sons.append(run_json(dict_[key]))
        return [x for sublist in animal_target_sons for x in sublist]
    run_json(dict_)
    

    然后调用run_json 会返回一个包含您想要的内容的列表。顺便说一句,我建议您将 json 从dict 重命名为,例如dict_,因为dict 是Python 的字典类型的保留字。

    【讨论】:

    • 有没有不使用全局变量的方法?我可以让它返回一个数组吗?
    • 每次我调用这个函数时,它都会保留旧数据。如何清除它?
    • 好的,请查看我的新回复;)
    【解决方案2】:

    既然你得到了 JSON,为什么不使用 json 模块呢?这将为您进行解析,并允许您使用字典函数+特性来获取您需要的信息。

    #!/usr/bin/python2.7
    from __future__ import print_function
    import json
    
    # _somehow_ get your JSON in as a string. I'm calling it "jstr" for this 
    # example. 
    # Use the module to parse it 
    jdict = json.loads(jstr)
    
    # our dict has keys...
    # view -> Term0 -> keys-we're-interested-in
    
    templist = jdict["view"]["Term0"]
    
    results = {}
    
    for _el in range(len(templist)):
        if templist[_el]["FullName"] == "Animal Set":
            # this is the one we're interested in - and it's another list
            moretemp = templist[_el]["Relation6"]
            for _k in range(len(moretemp)):
                term7 = moretemp[_k]["Term7"][0]
                displayName = term7["Animal_Target_DisplayName"]
                fullName = term7["Animal_Target_FullName"]
                results[fullName] = displayName
    print("{0}".format(results))
    

    然后你可以转储results dict 纯文本,或者使用漂亮的打印:

    >>> print(json.dumps(results, indent=4))
    {
        "Animaltitle2": "Animaltitle2", 
        "Animalcustomer3": "Animalcustomer3", 
        "Animalfact_transaction4": "Animalfact_transaction4", 
        "Animaltheater1": "Animaltheater1"
    }
    

    【讨论】:

      猜你喜欢
      • 2011-10-27
      • 2015-06-01
      • 2020-05-02
      • 1970-01-01
      • 1970-01-01
      • 2019-10-17
      • 1970-01-01
      • 2022-06-15
      • 2018-03-15
      相关资源
      最近更新 更多