I am trying to find a particular JSON value by key using List Comprehension and Pydash. I know there are multiple ways to do that , but I am more specific to get it done using List Comprehension
and Pydash
.
I tried below code snippet, which is kind of working for dict
iteration but not for list
iteration.
import pydash as py_
data = {
"P1": "ss",
"P2": {
"P1": "cccc"
},
"P3": [
{
"P1": "aaa"
}
]
}
def findall(v, k):
if type(v) is list:
[findall(i,k) for i in v]
a= [py_.get(v,k)]+[findall(py_.get(v, k1), k) for k1 in v if type(v) == type({})]
return(a)
refs_= findall(data, 'P1')
refs_d = py_.compact(py_.chain(refs_).
flatten_deep().
value())
print(refs_d)
I am trying to get values for all P1
. Output should be ["ss","cccc","aaa"]