JSON to pandas DataFrame

后端 未结 11 1777
离开以前
离开以前 2020-11-22 05:46

What I am trying to do is extract elevation data from a google maps API along a path specified by latitude and longitude coordinates as follows:

from urllib2         


        
11条回答
  •  忘掉有多难
    2020-11-22 06:14

    I prefer a more generic method in which may be user doesn't prefer to give key 'results'. You can still flatten it by using a recursive approach of finding key having nested data or if you have key but your JSON is very nested. It is something like:

    from pandas import json_normalize
    
    def findnestedlist(js):
        for i in js.keys():
            if isinstance(js[i],list):
                return js[i]
        for v in js.values():
            if isinstance(v,dict):
                return check_list(v)
    
    
    def recursive_lookup(k, d):
        if k in d:
            return d[k]
        for v in d.values():
            if isinstance(v, dict):
                return recursive_lookup(k, v)
        return None
    
    def flat_json(content,key):
        nested_list = []
        js = json.loads(content)
        if key is None or key == '':
            nested_list = findnestedlist(js)
        else:
            nested_list = recursive_lookup(key, js)
        return json_normalize(nested_list,sep="_")
    
    key = "results" # If you don't have it, give it None
    
    csv_data = flat_json(your_json_string,root_key)
    print(csv_data)
    

提交回复
热议问题