Ad

Python - Parse Complex JSON With Objectpath

- 1 answer

i need parse terraform file, write in JSON format. I have to extract two data, resource and id, this is example file:

    {
      "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"
                }
              }
            }
          }
        }
      ]
    }

I need export for any resources, the first key and value of id, in this case, aws_security_group.vpc-xxxxxxx-test-1sg-xxxxxxxxxxxxxx and aws_security_group.vpc-xxxxxxx-test-2sg-yyyyyyyyyyyy I have tried to write this in 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 is

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

It's'ok but I can't extract the id, any help is appreciated, also use other methods

Thanks

Ad

Answer

I don't know objectpath, but I think you need:

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

or even just

tree.execute('$..resources[0]..id')
Ad
source: stackoverflow.com
Ad