简体   繁体   中英

Python - Parse complex JSON with objectpath

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-1 sg-xxxxxxxxxxxxxx and aws_security_group.vpc-xxxxxxx-test-2 sg-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

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

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

or even just

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM