How to find a particular json value by key?

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

    I had the same issue just the other day. I wound up just searching through the entire object and accounted for both lists and dicts. The following snippets allows you to search for the first occurrence of a multiple keys.

    import json
    
    def deep_search(needles, haystack):
        found = {}
        if type(needles) != type([]):
            needles = [needles]
    
        if type(haystack) == type(dict()):
            for needle in needles:
                if needle in haystack.keys():
                    found[needle] = haystack[needle]
                elif len(haystack.keys()) > 0:
                    for key in haystack.keys():
                        result = deep_search(needle, haystack[key])
                        if result:
                            for k, v in result.items():
                                found[k] = v
        elif type(haystack) == type([]):
            for node in haystack:
                result = deep_search(needles, node)
                if result:
                    for k, v in result.items():
                        found[k] = v
        return found
    
    deep_search(["P1", "P3"], json.loads(json_string))
    

    It returns a dict with the keys being the keys searched for. Haystack is expected to be a Python object already, so you have to do json.loads before passing it to deep_search.

    Any comments for optimization are welcomed!

提交回复
热议问题