How to find a particular json value by key?

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

    You could also use a generator to search the object after json.load().

    Code example from my answer here: https://stackoverflow.com/a/39016088/5250939

    def item_generator(json_input, lookup_key):
        if isinstance(json_input, dict):
            for k, v in json_input.iteritems():
                if k == lookup_key:
                    yield v
                else:
                    for child_val in item_generator(v, lookup_key):
                        yield child_val
        elif isinstance(json_input, list):
            for item in json_input:
                for item_val in item_generator(item, lookup_key):
                    yield item_val
    

提交回复
热议问题