How to find a particular json value by key?

前端 未结 8 1836
再見小時候
再見小時候 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:51

    Using json to convert the json to Python objects and then going through recursively works best. This example does include going through lists.

    import json
    def get_all(myjson, key):
        if type(myjson) == str:
            myjson = json.loads(myjson)
        if type(myjson) is dict:
            for jsonkey in myjson:
                if type(myjson[jsonkey]) in (list, dict):
                    get_all(myjson[jsonkey], key)
                elif jsonkey == key:
                    print myjson[jsonkey]
        elif type(myjson) is list:
            for item in myjson:
                if type(item) in (list, dict):
                    get_all(item, key)
    

提交回复
热议问题