[英]Python - Parse complex JSON with objectpath
我需要解析terraform文件,以JSON格式编写。 我必须提取两个数据, resource
和id
,这是示例文件:
{
"version": 1,
"serial": 1,
"modules": [
{
"path": [
"root"
],
"outputs": {
},
"resources": {
"aws_security_group.vpc-xxxxxxx-test-1": {
"type": "aws_security_group",
"primary": {
"id": "sg-xxxxxxxxxxxxxx",
"attributes": {
"description": "test-1",
"name": "test-1"
}
}
},
"aws_security_group.vpc-xxxxxxx-test-2": {
"type": "aws_security_group",
"primary": {
"id": "sg-yyyyyyyyyyyy",
"attributes": {
"description": "test-2",
"name": "test-2"
}
}
}
}
}
]
}
我需要导出任何resources
,第一个键和id
值,在这种情况下, aws_security_group.vpc-xxxxxxx-test-1
sg-xxxxxxxxxxxxxx
和aws_security_group.vpc-xxxxxxx-test-2
sg-yyyyyyyyyyyy
在python中:
#!/usr/bin/python3.6
import json
import objectpath
with open('file.json') as json_file:
data = json.load(json_file)
json_tree = objectpath.Tree(data['modules'])
result = tuple(json_tree.execute('$..resources[0]'))
result
是
(“ aws_security_group.vpc-xxxxxxx-test-1”,“ aws_security_group.vpc-xxxxxxx-test-2”)
可以,但是我无法提取id
,我们将不胜感激,也可以使用其他方法
谢谢
我不知道对象路径,但是我认为您需要:
tree.execute('$..resources[0]..primary.id')
甚至只是
tree.execute('$..resources[0]..id')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.