如何将input.json转换为output.json?
我找到了Python flatten/unflatten 和Json flatten但不符合我的需要。
input.json
{
"root": {
"d3": {
"Selections": [
"d3.select",
"d3.selectAll"
],
"Transitions": [
"d3.transition"
]
}
}
}
output.json
{
"name": "root",
"children": [{
"name": "d3",
"children": [{
"name": "Selection",
"children": [{
"name": "d3.select"
}, {
"name": "d3.selectAll"
}]
}, {
"name": "Transitions",
"children": [{
"name": "d3.transition"
}]
}]
}]
}
答案 0 :(得分:0)
我可以使用以下代码完成它。根据"选择"输出不完全是顺序。 && 34; Transitions"和" name" vs"孩子",但我对此很好。
Python代码:
id|start|end
2|1994-05-01|1996-11-04
4|1979-07-18|
5|2005-02-01|2009-09-17
5|2010-10-01|2012-10-06
输出是(用#!/usr/bin/env python2
import json
import sys
def load_data(filename):
with open(filename) as data_file:
data = json.load(data_file)
return data
def json_pprint(json_obj):
print json.dumps(json_obj,
sort_keys=False, indent=2, separators=(',', ': '))
def flatten_list(mylist):
result = []
for item in mylist:
entry = {}
entry["name"] = item
result.append(entry)
return result
def smart_flatten(myobj):
if isinstance(myobj, list):
result_list = flatten_list(myobj);
return result_list;
if isinstance(myobj, dict):
result_list = []
for key, value in myobj.iteritems():
r = {}
r["name"] = key
r["children"] = smart_flatten(value)
result_list.append(r)
return result_list;
if __name__ == "__main__":
data = load_data("input.json")
####data = load_data(sys.stdin)
mydict = smart_flatten(data)
json_pprint(mydict)
包装结果):
[]