How to find a particular json value by key?

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

    I don't think there's any way of finding all values associated with P1 without iterating over the whole structure. Here's a recursive way to do it that first deserializes the json object in a file into an equivalent Python object. To simplify things most of the work is done via a private nested function.

    def find_values(id, obj):
        results = []
    
        def _find_values(id, obj):
            try:
                for key, value in obj.iteritems():
                    if key == id:
                        results.append(value)
                    elif not isinstance(value, basestring):
                        _find_values(id, value)
            except AttributeError:
                pass
    
            try:
                for item in obj:
                    if not isinstance(item, basestring):
                        _find_values(id, item)
            except TypeError:
                pass
    
        if not isinstance(obj, basestring):
            _find_values(id, obj)
        return results
    
    import json
    
    with open('data.json') as json_file:
        obj = json.load(json_file)
    
    print find_values('P1', obj)
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题