How to find a particular json value by key?

前端 未结 8 1839
再見小時候
再見小時候 2020-11-29 04:23

There is a json like this:

{
  \"P1\": \"ss\",
  \"Id\": 1234,
  \"P2\": {
      \"P1\": \"cccc\"
  },
  \"P3\": [
      {
          \"P1\": \"aaa\"
      }
         


        
8条回答
  •  南方客
    南方客 (楼主)
    2020-11-29 04:36

    Converting the JSON to Python and recursively searching is by far the easiest:

    def findall(v, k):
      if type(v) == type({}):
         for k1 in v:
             if k1 == k:
                print v[k1]
             findall(v[k1], k)
    
    findall(json.loads(a), 'P1')
    

    (where a is the string)

    The example code ignores arrays. Adding that is left as an exercise.

提交回复
热议问题