1

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"]

curiousguy
  • 3,212
  • 8
  • 39
  • 71
  • Why are you doing things like `type(v) == type({})`? You clearly understand that you can do `type(v) is list`.... although, more idiomatically you should be using `isinstance` although there is a subtle difference – juanpa.arrivillaga May 10 '21 at 18:37
  • 1
    Anyway, I think your main problem is *you don't do anything* when `type(v) is list`, you create a list, then discard it. Perhaps you meant `return [findall(i, k) for i in v]` But you haven't really described what your code *should do* – juanpa.arrivillaga May 10 '21 at 18:39
  • Yes `return [findall(i, k) for i in v]` thats where I made the mistake – curiousguy May 10 '21 at 18:49

0 Answers0