I have 2 json input
json 1:
[{
"Name": "John",
"Age": "23",
"Des": "SE"
},
{
"Name": "Rai",
"Age": "33",
"Des": "SSE"
},
{
"Name": "James",
"Age": "42",
"Des": "SE"
}
]
json 2:
[{
"Name": "John",
"Age": "23",
"Des": "SE",
"tech": [{
"Primary": ".net",
"secondary": "java",
"current": [{
"first": "Angular",
"second": "Spring"
}]
}]
},
{
"Name": "Ray",
"Age": "39",
"Des": "TE"
}
]
when the Name, age and Des parameters match. how to check a particular value for example "Spring" is present in the json 2, if present the desired output is present below
Desired output:
[{
"Name": "John",
"Age": "23",
"Des": "SE",
"tech": [{
"Primary": ".net",
"secondary": "java",
"current": [{
"first": "Angular",
"second": "Spring"
}]
}]
}]
I'm relatively new to python. please help me on this. Thanks
CodePudding user response:
You can try this code:
import json
a = """
[{
"Name": "John",
"Age": "23",
"Des": "SE"
},
{
"Name": "Rai",
"Age": "33",
"Des": "SSE"
},
{
"Name": "James",
"Age": "42",
"Des": "SE"
}
]
"""
b = """
[{
"Name": "John",
"Age": "23",
"Des": "SE",
"tech": [{
"Primary": ".net",
"secondary": "java",
"current": [{
"first": "Angular",
"second": "Spring"
}]
}]
},
{
"Name": "Ray",
"Age": "39",
"Des": "TE"
}
]
"""
# Covert to list dict python
json_dict1 = json.loads(a)
json_dict2 = json.loads(b)
def has_value(obj, val):
if isinstance(obj, dict):
values = obj.values()
elif isinstance(obj, list):
values = obj
if val in values:
return True
for v in values:
if isinstance(v, (dict, list)) and has_value(v, val):
return True
return False
elems = set((d['Name'], d['Age'], d['Des']) for d in json_dict1)
for e in json_dict2:
if (e['Name'], e['Age'], e['Des']) in elems and has_value(e, "Spring"):
print(e)
Reference for check Spring: How to know if a value exists in a list within a nested dictionary
