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

Python - Parse complex JSON with 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"
                }
              }
            }
          }
        }
      ]
    }

我需要导出任何 resourcesid 的第一个键和值,在本例中,aws_security_group.vpc-xxxxxxx-test-1 sg-xxxxxxxxxxxxxxaws_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')