如何获取用于更改Json的键值

时间:2019-01-09 23:11:10

标签: python json python-2.7

我正在使用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的嵌套结构始终在变化,但其键是总是一样。

2 个答案:

答案 0 :(得分:1)

我想您唯一的选择正在整个字典中运行并获取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对于字典类型的保留字。

答案 1 :(得分:-1)

既然获取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字典简单地或漂亮地打印出来:

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