Reputation: 1691
I have the following problem. Using Python 2.7, I have a JSON and I have to find all occurrences of key "workers".
the value is always a list of integers
workers : [22,14,523,...]
and I have to compare them with some other list of integers.
ID = [14,22,26,32,...]
in case in workers list one number is missing from ID list that number in workers has to be removed.
I hope I have made this clear enough.
The problem is this is a nested JSON with different levels.
Any suggestions ?
Thank you
Upvotes: 4
Views: 1441
Reputation: 5329
You can see an example below. I hope you meant a similar solution.
test_ids_1 = [1, 2, 3, 4, 5, 6]
test_ids_2 = [1, 2, 3, 4, 5, 8]
json_var = [
{
"human": {"man":
{"workers": [1, 2, 3],
"blabla": "abcd"},
"woman":
{"workers": [4, 5, 6],
"blabla": "dcab"}}
}
]
for worker in json_var[0]["human"]:
for ids in json_var[0]["human"][worker]["workers"]:
if ids not in test_ids_1:
print("%s is missing from test_ids_1 list" % ids)
if ids not in test_ids_2:
print("%s is missing from test_ids_2 list" % ids)
Output:
python test.py
6 is missing from test_ids_2 list
Note: Of course, if you read the Json file and serialize it then you can iterate on it and check the elements. You can see details on this link: https://docs.python.org/2/library/json.html
Upvotes: 2