javascript
java json.pasent_来自CSV的带有id parent(Python)的JSON树
我想這就是你想要的:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# https://stackoverflow.com/questions/53687467/json-tree-from-csv-with-idparent-python
# Just: how to make that "return" give the 'childs': { placeholder: 'Select', items: { ........... } } in that form.
import csv
import re
from collections import defaultdict
from pprint import pprint
def find_branch(node, branch_key):
for key, item in node.items():
if key == branch_key:
return item
else:
child_node = find_branch(node[key]['children']['items'], branch_key)
if child_node:
return child_node
return None
tree = {}
with open('data.csv') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
next(reader)
for row in reader:
item_id, name, admin_level, parent_id = row
item_id = 'lc' + item_id
parent_id = 'lc' + parent_id if parent_id else None
if parent_id:
parent_branch = find_branch(tree, parent_id)
if parent_branch:
parent_branch['children']['items'][item_id] = dict(name=name, children=dict(placeholder='Select', items={}))
else:
print('Branch %s (%s) not found.' % (item_id, name))
# raise Exception('Branch %s (%s) not found.' % (id, name))
else:
tree[item_id] = dict(name=name, children=dict(placeholder='Select', items={}))
pprint(tree)
哪個產生這個輸出:
{'lc295480': {'children': {'items': {'lc2897141': {'children': {'items': {'lc5400843': {'children': {'items': {},
'placeholder': 'Select'},
'name': 'Loures'},
'lc5400844': {'children': {'items': {},
'placeholder': 'Select'},
'name': 'Mafra'}},
'placeholder': 'Select'},
'name': 'Lisboa'},
'lc3920249': {'children': {'items': {},
'placeholder': 'Select'},
'name': 'Aveiro'},
'lc5011694': {'children': {'items': {},
'placeholder': 'Select'},
'name': 'Leiria'}},
'placeholder': 'Select'},
'name': 'Portugal'}}
總結
以上是生活随笔為你收集整理的java json.pasent_来自CSV的带有id parent(Python)的JSON树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java调用so库中的native方法_
- 下一篇: hsv java_rgb-hsv-hsl