[英]How can I access the nested data in this complex JSON, which includes another JSON document as one of the strings?
[英]How can I query complex nested JSON data in Python
我有以下 JSON 数据,它是 AWS“cli 描述 ec2 数据”输出的缩短版本。
我需要使用 Python 以便查询 InstanceId 值并获取其所有 VolumeId 值(可能有 1 个以上的条目)及其 PrivateIpAddress 值。
输出看起来像这样:
i-01,10.1.1.1,vol-123,vol-456
i-02,10.2.2.2,vol-789
我是 Python 新手,似乎无法找到有关如何执行此操作的答案。 任何人都可以帮忙吗?
{
"Reservations": [
{
"Instances": [
{
"InstanceId": "i-01",
"PrivateIpAddress": "10.1.1.1",
"BlockDeviceMappings": [
{
"DeviceName": "/dev/sda",
"Ebs": {
"Status": "attached",
"VolumeId": "vol-123",
}
},
{
"DeviceName": "/dev/sdb",
"Ebs": {
"Status": "attached",
"VolumeId": "vol-456",
}
}
],
"Tags": [
{
"Value": "Server01",
"Key": "Name"
}
],
"AmiLaunchIndex": 0
}
],
"OwnerId": "123456789"
},
{
"Instances": [
{
"InstanceId": "i-02",
"PrivateIpAddress": "10.2.2.2",
"BlockDeviceMappings": [
{
"DeviceName": "/dev/sda",
"Ebs": {
"Status": "attached",
"VolumeId": "vol-789",
}
}
],
"Tags": [
{
"Value": "Server02",
"Key": "Name"
}
],
"AmiLaunchIndex": 0
}
],
"OwnerId": "123456789"
}
]
}
result = []
for reservation in d["Reservations"]:
res = {}
instances = reservation["Instances"][0]
res['InstanceID'] = instances['InstanceId']
res['PrivateIpAddress'] = instances['PrivateIpAddress']
res['BlockDeviceMappings'] = []
for blockdevice in instances['BlockDeviceMappings']:
res['BlockDeviceMappings'].append(blockdevice['Ebs']['VolumeId'])
result.append(res)
然后你可以这样做:
final_df = pd.DataFrame(result)
以漂亮的方式显示结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.