I have this Json as string:
json_String= {
"type": [
{
"color": "blue",
"contrast": "high",
"stock": "enough"
},
{
"color": "orange",
"contrast": "high",
"stock": "enough",
"details": "noneTobeGiven"
},
{
"color": "red",
"contrast": "low",
"stock": "enough",
"details": "noneTobeGiven"
},
{
"color": "blue",
"contrast": "high",
"stock": "enough",
"details": "noneTobeGiven"
}
]
}
creating a dict from it:
dict1 = eval(json_String)
Based on this answer I'm tring to return all the occurances of a tag for a specific path
from functools import reduce # forward compatibility for Python 3
import operator
def get_by_path(root, items):
"""Access a nested object in root by item sequence."""
return reduce(operator.getitem, items, root)
print(get_by_path(dict1, ["type", "color"]))
But an error is received :
TypeError: list indices must be integers or slices, not str
I assume this is because of the list and it expects an index instead of str, and tried to call the module as such :
print(get_by_path(dict1, ["type", "color"][0]))
The result was :
return reduce(operator.getitem, items, root)
KeyError: 't'
Goal
For a given path, lets say type.color, to return all the values for [color] for every occurance:
print(get_values_by_path("type.color")
["blue", "orange", "red", "blue"]