简体   繁体   English

如何提取嵌套的JSON数据?

[英]How to extract nested JSON data?

I am trying to get a value from a data JSON. 我正在尝试从数据JSON获取值。 I have successfully traversed deep into the JSON data and almost have what I need! 我已经成功遍历了JSON数据,几乎满足了我的需求!

Running this command in Python : autoscaling_name = response['Reservations'][0]['Instances'][0]['Tags'] 在Python中运行以下命令: autoscaling_name = response['Reservations'][0]['Instances'][0]['Tags']

Gives me this : 给我这个:

'Tags': [{'Key': 'Name', 'Value': 'Trove-Dev-Inst : App WebServer'}, {'Key': 'aws:autoscaling:groupName', 'Value': 'CodeDeploy_Ernie-dev-Autoscaling-Deploy_d-4WTRTRTRT'}, {'Key': 'CodeDeployProvisioningDeploymentId', 'Value': 'd-4WTRTRTRT'}, {'Key': 'Environment', 'Value': 'ernie-dev'}]

I only want to get the value "CodeDeploy_Ernie-dev-Autoscaling-Deploy_d-4WTRTRTRT" . 我只想获取值"CodeDeploy_Ernie-dev-Autoscaling-Deploy_d-4WTRTRTRT" This is from the key "aws:autoscaling:groupName" . 这是从键"aws:autoscaling:groupName"

How can I further my command to only return the value "CodeDeploy_Ernie-dev-Autoscaling-Deploy_d-4WTRTRTRT" ? 如何进一步执行命令,仅返回值"CodeDeploy_Ernie-dev-Autoscaling-Deploy_d-4WTRTRTRT"

Is this the full output? 这是完整的输出吗? This a dictionary containing a list with nested dictionaries, so you should treat it that way. 这本字典包含带有嵌套字典的列表,因此您应该这样处理。 Suppose it is called: 假设它被称为:

A = {
    "Tags": [
        {
            "Key": "Name",
            "Value": "Trove-Dev-Inst : App WebServer"
        },
        {
            "Key": "aws:autoscaling:groupName",
            "Value": "CodeDeploy_Ernie-dev-Autoscaling-Deploy_d-4WTRTRTRT"
        },
        {
            "Key": "CodeDeployProvisioningDeploymentId",
            "Value": "d-4WTRTRTRT"
        },
        {
            "Key": "Environment",
            "Value": "ernie-dev"
        }
    ]
}

Your first adress the object, then its key in the dictionary, the index within the list and the key for that dictionary: 您的第一个地址是对象,然后是字典中的键,列表中的索引以及该字典的键:

print(A['Tags'][1]['Value'])

Output: 输出:

CodeDeploy_Ernie-dev-Autoscaling-Deploy_d-4WTRTRTRT

EDIT: Based on what you are getting then you should try: 编辑:根据您所得到的然后您应该尝试:

autoscaling_name = response['Reservations'][0]['Instances'][0]['Tags'][1]['Value']

You could also use glom it's great for deeply nested functions and has sooo many uses that make complicated nested tasks easy. 您还可以使用glom这对于深度嵌套的函数非常有用,并且具有许多用途,可简化复杂的嵌套任务。

For example translating @Celius's answer: 例如,翻译@Celius的答案:

glom(A, 'Tags.1.Value')

Returns the same thing: 返回相同的内容:

CodeDeploy_Ernie-dev-Autoscaling-Deploy_d-4WTRTRTRT

So to answer your original question you'd use: 因此,要回答您的原始问题,您将使用:

glom(response, 'Reservations.0.Instances.0.Tags.1.Value')

The final code for this is - 最终的代码是-

    tags = response['Reservations'][0]['Instances'][0]['Tags']
    autoscaling_name = next(t["Value"] for t in tags if t["Key"] == "aws:autoscaling:groupName")

This also ensures that if the order of the data is moved in the JSON data it will still find the correct one. 这还可以确保,如果将数据的顺序移至JSON数据中,它仍将找到正确的顺序。

For anyone struggling to get their heads around list comprehensions and iterators, the cherrypicker package ( pip install --user cherrypicker ) does this sort of thing for you pretty easily: 对于任何想尽力了解列表理解和迭代器的人, cherrypicker软件包( pip install --user cherrypicker )为您轻松完成以下任务:

from cherrypicker import CherryPicker

tags = CherryPicker(response['Reservations'][0]['Instances'][0]['Tags'])

tags(Key="aws:autoscaling:groupName")[0]["Value"].get()

which gives you 'CodeDeploy_Ernie-dev-Autoscaling-Deploy_d-4WTRTRTRT' . 这将为您提供'CodeDeploy_Ernie-dev-Autoscaling-Deploy_d-4WTRTRTRT' If you're expecting multiple values, omit the [0] to get back a list of all values that have an associated "aws:autoscaling:groupName" key. 如果期望多个值,请省略[0]以返回具有关联的"aws:autoscaling:groupName"键的所有值的列表。

This is probably all a bit overkill for your question, which can be solved easily with a simple list comprehension. 对于您的问题,这可能有点矫kill过正,只需简单的列表理解即可轻松解决。 But this approach might come in handy if you need to do more complicated things later, like matching on partial keys only (eg aws:* or something more complicated like a regular expression), or you need to filter based on the values in an intermediate layer of the nested object. 但是,如果您以后需要做更复杂的事情,例如只匹配部分键(例如aws:*或更复杂的东西,例如正则表达式),或者需要根据中间值进行过滤,则此方法可能会派上用场嵌套对象的图层。 This sort of task could lead to lots of complicated nested for loops or list comprehensions, whereas with CherryPicker it stays as a simple, potentially one-line command. 这种任务可能会导致许多复杂的嵌套循环或列表理解,而对于CherryPicker,它只是一个简单的可能单行的命令。

You can find out more about advanced usage at https://cherrypicker.readthedocs.io . 您可以在https://cherrypicker.readthedocs.io上找到有关高级用法的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM