栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将CSV转换为JSON树结构?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将CSV转换为JSON树结构?

使用defaultdict从馆藏标准库赚了很多的具有层次结构简单,可解决的问题。因此,我为您的问题开发了示例解决方案。但是在运行脚本之前,请确保已用逗号分隔了csv文件(名为test.csv),或者可以在此处更改csv阅读器逻辑。

这是我测试脚本的csv文件。

condition, target, sub, duboxygen,tree,G1,T1oxygen,tree,G2,T1oxygen,tree,G2,T2water,car,G3,T1water,tree,GZ,T1water,tree,GZ,T2fire,car,GTD,T3oxygen,bomb,GYYS,T1

从技术上讲,该脚本应适用于具有各种尺寸的任何类型的csv文件。但是您需要自己进行测试才能确定。

import csvfrom collections import defaultdictdef ctree():    """ One of the python gems. Making possible to have dynamic tree structure.    """    return defaultdict(ctree)def build_leaf(name, leaf):    """ Recursive function to build desired custom tree structure    """    res = {"name": name}    # add children node if the leaf actually has any children    if len(leaf.keys()) > 0:        res["children"] = [build_leaf(k, v) for k, v in leaf.items()]    return resdef main():    """ The main thread composed from two parts.    First it's parsing the csv file and builds a tree hierarchy from it.    Second it's recursively iterating over the tree and building custom    json-like structure (via dict).    And the last part is just printing the result.    """    tree = ctree()    # NOTE: you need to have test.csv file as neighbor to this file    with open('test.csv') as csvfile:        reader = csv.reader(csvfile)        for rid, row in enumerate(reader): # skipping first header row. remove this logic if your csv is # headerless if rid == 0:     continue # usage of python magic to construct dynamic tree structure and # basically grouping csv values under their parents leaf = tree[row[0]] for cid in range(1, len(row)):     leaf = leaf[row[cid]]    # building a custom tree structure    res = []    for name, leaf in tree.items():        res.append(build_leaf(name, leaf))    # printing results into the terminal    import json    print(json.dumps(res))# so let's rollmain()

这是结果的json片段:

{    "name": "oxygen",    "children": [      {        "name": "tree",        "children": [          { "name": "G2", "children": [   {     "name": "T2"   },   {     "name": "T1"   } ]          },          { "name": "G1", "children": [   {     "name": "T1"   } ]          }        ]      },      {        "name": "bomb",        "children": [          { "name": "GYYS", "children": [   {     "name": "T1"   } ]          }        ]      }    ]  }

请让我知道是否还有其他问题。快乐的pythonning;)



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/404207.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号