Decoding nested JSON with multiple 'for' loops

后端 未结 3 1150

I\'m new to Python (last week), and have reached my limit. Spent three days on this, most of my time in stackoverflow, but I cannot work out how to go any further!

T

3条回答
  •  旧巷少年郎
    2021-01-16 16:10

    It looks ugly, but you can refine this, but here is listing at arbitrary depth of mix of Dict and List:

    import os, json,requests
    print 'Starting'
    url = 'https://dl.dropboxusercontent.com/u/3758695/json.txt'
    
    # download the json string
    json_string = requests.get(url)
    print 'Downloaded json'
    
    def dig_down(partial_json_list, depth):
        if type(partial_json_list) is list:
            for i in range(len(partial_json_list)):
                print 'index', i, ' at depth', depth,' has', len(partial_json_list[i]) , 'elements'
                if len(partial_json_list[i]) > 1:
                    dig_down(partial_json_list[i],depth+1)
        else:
            for k in partial_json_list:
                print 'item at depth', depth, 'equals', k#, ' & has', len(partial_json_list[k]) , 'elements'
                if type(partial_json_list) is list or type(partial_json_list) is dict:
                    try:
                        if len(partial_json_list[k]) > 1:
                            dig_down(partial_json_list[k],depth+1)
                    except:
                        pass
                else:
                    print partial_json_list[k]
    
    # get the content
    the_data = json_string.json()
    print 'the_data has length ', len(the_data)
    dig_down(the_data,0)
    

提交回复
热议问题