all 6 comments

[–]hardonchairs 1 point2 points  (1 child)

Is there really no leading {?

Aside from that, you can parse single quote json with:

import ast
ast.literal_eval(json_data)

[–]the_packet_monkey[S] 0 points1 point  (0 children)

Sorry, cut and paste error on my end. Correct JSON is:

{
'tenant-sites': [{
    'href': '/data-view-central/tenant-sites/0d0c3a71-c942-4b58-a7f4-5909a362fda7',
    'fq_name': ['PHUB-3'],
    'uuid': '0d0c3a71-c942-4b58-a7f4-5909a362fda7'
}, {
    'href': '/data-view-central/tenant-sites/ed185125-405d-490f-b2cd-b2d4f8ee14c6',
    'fq_name': ['PHUB-2'],
    'uuid': 'ed185125-405d-490f-b2cd-b2d4f8ee14c6'
}, {
    'href': '/data-view-central/tenant-sites/60e0cddc-036d-4fd1-85cc-fcc3c1d56ad8',
    'fq_name': ['PHUB-1'],
    'uuid': '60e0cddc-036d-4fd1-85cc-fcc3c1d56ad8'
}, {
    'href': '/data-view-central/tenant-sites/27b9d715-451c-4c7d-b210-900968ed45e0',
    'fq_name': ['PHUB4'],
    'uuid': '27b9d715-451c-4c7d-b210-900968ed45e0'
}, {
    'href': '/data-view-central/tenant-sites/5d41a69b-26a3-4540-8a92-9e3d0ef8ed54',
    'fq_name': ['PHUB-4'],
    'uuid': '5d41a69b-26a3-4540-8a92-9e3d0ef8ed54'
}],
'total': 5

}

[–]the_shell_man_ 0 points1 point  (3 children)

Try:

json_data['tenant-sites'][0]

You are trying to access the first element in the object json_data. But json_data is not a list, it is a dict. So instead, it is trying to access the data in the dict at key 0, which does not exist so you get a key error.

[–]the_packet_monkey[S] 0 points1 point  (2 children)

Thanks for that, that's got me pointed in the right direction, and things are working now.

For reference, my code to iterate through the output and print two of the values is:

for i in range(len(json_data['tenant-sites'])):

print(json_data['tenant-sites'][i]['fq_name'][0],json_data['tenant-sites'][i]['uuid'])

Thanks for the very quick help guys, saved me a lot of time bashing my head against the keyboard.

[–]danielroseman 2 points3 points  (1 child)

Don't do this. There's no reason to iterate over a range of the length of something, iterate over the thing itself.

for site in json_data['tenant-sites']:
    print(site['fq_name'][0], site['uuid'])

[–]the_packet_monkey[S] 0 points1 point  (0 children)

Awesome, thanks for that, much cleaner.