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

2024-04-24 16:51:44 发布

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

我用的是python2.7

我有一个json,当我请求它时,它总是在变化。你知道吗

我需要在dict中的Relation6下的Term7下拉出动物\目标\显示名称

问题是,有时对象关系6位于Json的另一部分,它可以更深层次或以另一种顺序排列。你知道吗

我正在尝试创建只导出键Animal_Target_DisplayName的值的代码,但是什么都不起作用。它甚至不会循环嵌套的dict

现在,如果我使用['view']['Term0'][0]['Relation6']之类的方法将其拉出,就可以工作了,但是请记住,JSON永远不会以相同的结构返回。你知道吗

我正在使用的代码来获取键Animal_Target_DisplayName的值,但它似乎没有在dict中循环并找到该键的所有值。你知道吗

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的嵌套结构总是变化的,但是它的键总是相同的。你知道吗


Tags: idtargetvaluetagdicttransactionfullnameanimal
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))

然后您可以转储resultsdict plain,或者使用漂亮的打印:

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

我想您唯一的选择是运行整个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的字典类型的保留字。你知道吗

相关问题 更多 >