for an input Json,
[{
"ID": "00300000-0000-0000-0000-000000000000",
"CommonTags": [
"Sports"
],
"subID": "149f43d0-6fa9-44f3-b4ba-6fb7a320d0a4",
"Description": "Sports,Arts",
"Title": "Biodata",
"index": 1,
"Value": "Availabity"
},
{
"ID": "00400000-0000-0000-0000-000000000000",
"CommonTags": [
"Social Media"
],
"subID": "149f43d0-6fa9-44f3-b4ba-6fb7a320d0a4",
"Description": "Sports,Arts",
"Title": "Biodata",
"index": 5,
"Value": "Availabity"
},
{
"ID": "07300000-0000-0000-0000-000000000079",
"CommonTags": [
"Sports"
],
"subID": "149f43d0-6fa9-44f3-b4ba-6fb7a320d0a4",
"Description": "Environmental Science",
"Title": "Biodata",
"index": 1,
"Value": "Performace"
}
]
I want only the some necessary fields such as ID,CommonTags,Value. my approach for this, by the utilization of for loops and fetch and store the necessary values.
Is there any possibility like model we use in ASP.net and get only the necessary values in python.
I'm relatively fresher to python language. Please suggest if there's an alternative to utilization of for loops.
Desired Output:
[
{
"ID": "00300000-0000-0000-0000-000000000000",
"CommonTags": "Sports",
"Value": "Availability"
},
{
"ID": "00400000-0000-0000-0000-000000000000",
"CommonTags": "Social Media",
"Value": "Availability"
},
{
"ID": "07300000-0000-0000-0000-000000000079",
"CommonTags": "Sports",
"Value": "Performance"
}
]
CodePudding user response:
List comprehension that iterates over the dicts with a dict comprehension that filters the necessary fields seem to do the job:
out = [{k: (v[0] if isinstance(v, list) and len(v)==1 else v) for k,v in d.items()
if k in ['ID','CommonTags','Value']} for d in lst]
Output:
[{'ID': '00300000-0000-0000-0000-000000000000',
'CommonTags': 'Sports',
'Value': 'Availabity'},
{'ID': '00400000-0000-0000-0000-000000000000',
'CommonTags': 'Social Media',
'Value': 'Availabity'},
{'ID': '07300000-0000-0000-0000-000000000079',
'CommonTags': 'Sports',
'Value': 'Performace'}]
CodePudding user response:
glom allows you to define a spec (model) to do so.
>>> from glom import glom
>>> spec = [ dict(ID='ID', CommonTags=('CommonTags', '0'), Value='Value') ]
Result:
>>> glom(target, spec)
[{'ID': '00300000-0000-0000-0000-000000000000',
'CommonTags': 'Sports',
'Value': 'Availability'},
{'ID': '00400000-0000-0000-0000-000000000000',
'CommonTags': 'Social Media',
'Value': 'Availability'},
{'ID': '07300000-0000-0000-0000-000000000079',
'CommonTags': 'Sports',
'Value': 'Performance'}]