Python json nested

Question:

I have a problem with a nested json in python script, i need to reproduce the following jq query:

cat inventory.json | jq '.hostvars[] | [.openstack.hostname, .openstack.accessIPv4]'

the json file has a structure like this:

{
  "hostvars": {
    "096b430e-20f0-4655-bb97-9bb3ab2db73c": {
      "openstack": {
        "accessIPv4": "192.168.3.6",
        "hostname": "vm-1"
        }
      }
    "8fb7b9b7-5ccc-47c8-addf-64563fdd0d4c": {
      "openstack": {
        "accessIPv4": "192.168.3.7",
        "hostname": "vm-2"
        }
      }
   }
}

and the query with jq gives me the correct output:

# cat test.json | jq '.hostvars[] | [.openstack.hostname, .openstack.accessIPv4]'
[
  "vm-1",
  "192.168.3.6"
]
[
  "vm-2",
  "192.168.3.7"
]

Now i want reproduce this in python, to handle the individual values in variable but I can’t parse the contents of each id, what with jq i do with .hostvars [].

with open('inventory.json', 'r') as inv:
    data=inv.read()

obj=json.loads(data)
objh=obj['hostvars'][096b430e-20f0-4655-bb97-9bb3ab2db73c]['openstack']

print(objh)

Calling the id works, but if I replace it with 0 or [] I have a syntax error.

Asked By: GabboPenna

||

Answers:

json_data = {
  "hostvars": {
    "096b430e-20f0-4655-bb97-9bb3ab2db73c": {
      "openstack": {
        "accessIPv4": "192.168.3.6",
        "hostname": "vm-1"
        }
      },
    "8fb7b9b7-5ccc-47c8-addf-64563fdd0d4c": {
      "openstack": {
        "accessIPv4": "192.168.3.7",
        "hostname": "vm-2"
        }
      }
   }
}

result = [[value['openstack']['hostname'], value['openstack']['accessIPv4']]
          for value in json_data['hostvars'].values()]
print(result)

output

[['vm-1', '192.168.3.6'], ['vm-2', '192.168.3.7']]
Answered By: buran

Serializing JSON Data

I think when you are dealing with json python you should use convert to Serializing:

The json module exposes two methods for serializing Python objects into JSON format.

dump()

will write Python data to a file-like object. We use this when we want to serialize our Python data to an external JSON file.

dumps()

will write Python data to a string in JSON format. This is useful if we want to use the JSON elsewhere in our program, or if we just want to print it to the console to check that it’s correct.

Both the dump() and dumps() methods allow us to specify an optional indent argument. This will change how many spaces is used for indentation, which can make our JSON easier to read.

json_str = json.dumps(data, indent=4)

for exampel:


 import json
    
data={"user":{
"name":"CodeView",
"age":29
}
}
with open("data_file.json","w")as write_file:
    json.dump(data,write_file)

json_str=json.dumps(data)
print(json_str)
Answered By: CodeView
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.