Brian Valle
Brian Valle

Reputation: 1

Parsing irregular JSON fields in Python

Consider this json format:

{
"HostSystem(\"host-527\")": {},
"HostSystem(\"host-487\")": {},
"HostSystem(\"host-482\")": {
    "hardware.cpuInfo.numCpuThreads": 2,
    "name": "192.168.1.1",
    "config.network.consoleVnic": [],
    "capability.perVmSwapFiles": true,
    "capability.maxRunningVMs": 0,
    "config.dateTimeInfo.timeZone.name": "UTC",
}

I'd like to parse out 'name' and 'hardware.cpuInfo.numCpuThreads' from each 'HostSystem' but I'm failing to read the key properly and it doesn't appear that I can use a wildcard.

This is my starter code to test out reading 'HostSystem *' and its failing miserably.

import json

with open("blob.json") as json_data:
    data = json.load(json_data)
    print data['HostSystem *']

Thanks for your suggestions.

Upvotes: 0

Views: 515

Answers (2)

cylee
cylee

Reputation: 570

Is your json data copied properly? If so, you're failing parsing json data because it's not valid format.

Check whether your json format is in a correct format in Online Json Editor (http://www.jsoneditoronline.org/). Your should delete comma at the end of "config.dateTimeInfo.timeZone.name": "UTC", and add } after it.

Upvotes: 0

Nish
Nish

Reputation: 189

Here it is:

import json

with open("blob.json") as json_data:
    data = json.load(json_data)

for k in data:
    if 'hardware.cpuInfo.numCpuThreads' in data[k]:
        print data[k]['hardware.cpuInfo.numCpuThreads']

Upvotes: 2

Related Questions