Python-使用对象路径解析复杂的JSON

时间:2019-04-03 08:09:00

标签: python python-2.7 objectpath

我需要解析terraform文件,以JSON格式编写。我必须提取两个数据resourceid,这是示例文件:

    {
      "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-xxxxxxxxxxxxxxaws_security_group.vpc-xxxxxxx-test-2 {{1} } 我试图用python来写这个:

sg-yyyyyyyyyyyy

#!/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]'))

  

('aws_security_group.vpc-xxxxxxx-test-1','aws_security_group.vpc-xxxxxxx-test-2')

没关系,但是我无法提取result,我们将不胜感激,也可以使用其他方法

谢谢

1 个答案:

答案 0 :(得分:1)

我不知道对象路径,但是我认为您需要:

tree.execute('$..resources[0]..primary.id')

甚至只是

tree.execute('$..resources[0]..id')