日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

java json.pasent_来自CSV的带有id parent(Python)的JSON树

發布時間:2025/3/19 51 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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树的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。