Parsing a single-level JSON file
MRAB
python at mrabarnett.plus.com
Fri Nov 18 13:38:56 EST 2016
On 2016-11-18 18:23, mike.reider at gmail.com wrote:
> hi all,
>
> Im reading in a JSON file that looks like this
>
>
> [
> {
> "name":"myField1",
> "searchable":true,
> "navigable":true,
> "custom":true,
> "clauseNames":[
> "cf[10190]",
> "Log Details"
> ],
> "orderable":true,
> "id":"customfield_10190",
> "schema":{
> "customId":10190,
> "type":"string",
> "custom":"com.atlassian.jira.plugin.system.customfieldtypes:textarea"
> }
> },
> {
> "name":"myField2",
> "searchable":true,
> "navigable":true,
> "custom":true,
> "clauseNames":[
> "cf[10072]",
> "Sellside Onboarding Checklist"
> ],
> "orderable":true,
> "id":"customfield_10072",
> "schema":{
> "items":"option",
> "customId":10072,
> "type":"array",
> "custom":"com.atlassian.jira.plugin.system.customfieldtypes:multicheckboxes"
> }
> }]
>
>
> Lets say I want to get the ID # of MyField1, how can I parse this with json lib? Theyre all on the same level, not sure how to target it to go to MyField1 and get "id" value.
>
> Thanks
>
Parsing it is easy:
with open(json_path) as json_file:
data_list = json.load(json_file)
If it's a one-off lookup, just do a linear search:
for entry in data_list:
if entry['name'] == 'myField1':
print('ID is {}'.format(entry['id']))
break
else:
print('Not found!')
If you're going to do multiple lookups, turn it into a dict, using the
'name' field as the key:
data_dict = {entry['name']: entry for entry in data_list}
if 'myField1' in data_dict:
print('ID is {}'.format(data_dict['myField1']['id']))
else:
print('Not found!')
More information about the Python-list
mailing list