Parsing a single-level JSON file
Peter Otten
__peter__ at web.de
Fri Nov 18 13:37:45 EST 2016
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.
>>> import json
>>> data = json.loads(s)
>>> [wanted] = [d["id"] for d in data if d["name"] == "myField1"]
>>> wanted
'customfield_10190'
If you need to do this often for the same data you can speed up the process
with a lookup table:
>>> lookup = {d["name"]: d["id"] for d in data}
>>> lookup["myField1"]
'customfield_10190'
>>> lookup["myField2"]
'customfield_10072'
I'm assuming that the names are unique.
More information about the Python-list
mailing list