I am currently working on a walking json where I could with parameters add in the walk I want to go through JSON. I have created something like this:
from collections import abc
def walk(obj, *path):
"""
Goes through the given json path. If it is found then return the given path else empty dict
"""
for segment in path:
if not isinstance(obj, abc.Mapping) or segment not in obj:
print(f"Couldn't walk path; {path}")
return {}
obj = obj[segment]
return obj
# -------------------------------------------------------- #
json_value = {
"id": "dc932304-dde4-3517-8b76-58081cc9dd0d",
"Information": [{
"merch": {
"id": "8fb66657-b93d-5f2d-8fe7-a5e355f0f3a8",
"status": "ACTIVE"
},
"value": {
"country": "SE IS BEST"
},
"View": {
"id": "9aae10f4-1b75-481d-ac5f-b17bc46675bd"
}
}],
"collectionTermIds": [
],
"resourceType": "thread",
"rollup": {
"totalThreads": 1,
"threads": [
]
},
"collectionsv2": {
"groupedCollectionTermIds": {
},
"collectionTermIds": [
]
}
}
# -------------------------------------------------------- #
t = walk(json_value, "Information", 0)
print(t)
My current problem is that I am trying to get the the first in a list from "Information" by giving the walk
function the value 0 as I provided however it returns that it couldn't due to Couldn't walk path; ('Information', 0)
I wonder how I can choose which list number I want to walk through by giving it into the parameter? e.g. if I would choose 1, it should return Couldn't walk path; ('Information', 1)
but if I choose to do 0
then it should return
{
"merch": {
"id": "8fb66657-b93d-5f2d-8fe7-a5e355f0f3a8",
"status": "ACTIVE"
},
"value": {
"country": "SE IS BEST"
},
"View": {
"id": "9aae10f4-1b75-481d-ac5f-b17bc46675bd"
}
}