将JSON树遍历代码从PHP转换为Python

时间:2014-07-09 20:57:55

标签: php python

我试图将以下代码从PHP翻译成Python。该代码旨在展平json树结构。你能帮我把它翻译成一个等价的Python函数吗?

  function flatten($parent,&$return,$stack=[]){
        foreach($parent as $child){
                $return[]=array_merge($stack,[$child->name]);
        }
  }

  $json=json_decode(file_get_contents('tmpfile.json'));
  $root=$json->report->data;

  $return=[];
  flatten($root,$return);
  print_r($return);

自问题解决以来,在Python中回答:

def flatten_two(parent, _return, stack = []):
    for child in parent:
        if 'breakdown' in child:
            flatten_two(child['breakdown'], _return, stack + [child['name']] )
        else:
            _return.append(stack + [child['name'], child['counts'][0]])


_return_list = []
flatten_two(report_data, _return_list)
print(_return_list)

1 个答案:

答案 0 :(得分:1)

类似于:

import json            

def flatten(x):
    if isinstance(x, list):
        return [a for i in x for a in flatten(i)]
    else:
        return [x]            

json.dumps(flatten(LoL))

LoL是json'd之前要展平的列表列表

或者,如果您从JSON开始:

flatten(json.loads('[1, 2, [3, 4, [5], ["nested"]], [6, [[[7, "deeper"]]]]]'))