python - 将 csv 转换为 JSON 树结构?

标签 python json csv d3.js tree

我读了这些问题:

但是我仍然无法将 csv 文件转换为 JSON 的层次结构。我在 stackoverflow 上找到的所有脚本都是针对特定问题的。假设必须对三个变量进行分组:

condition   target  sub
oxygen      tree    G1
oxygen      tree    G2
water       car     G3
water       tree    GZ
fire        car     GTD
oxygen      bomb    GYYS

这将产生一个像这样的 JSON 文件(据我所试):

oxygen
    - tree  
        - G1
        - G2
    - bomb
        -GYYS
water 
    - car
        - G3
    - tree
        -GZ
fire 
    - car   
        - GTD

并且这些必须以嵌套结构分组,例如:

    {
   "name": "oxygen",
   "children": [
    {
     "name": "tree",
     "children": [
      {"name": "G1"},
      {"name": "G2"},
      {"name": "GYYS"}
     ]
    },
    {
     "name": "bomb",
      "children": [
      {"name": "GYYS"}
     ]
    }
    ]
}
etc.

我尝试了这个站点上的每个脚本,但是我无法创建一个通用函数来创建一个 flare.json。我可以发布我的代码,但这就像上面提供的链接一样。所以我要求一个简单的代码(或一个可以帮助我的例子)将其转换为类似 flare.JSON 的结构。

最佳答案

使用 defaultdict来自 collections标准库使许多具有层次结构的问题变得容易和可解决。所以我为您的问题开发了一个示例解决方案。但在运行脚本之前,请确保您有逗号分隔的 csv 文件(名为 test.csv),或者您可以更改 csv reader那里的逻辑。

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

condition, target, sub, dub
oxygen,tree,G1,T1
oxygen,tree,G2,T1
oxygen,tree,G2,T2
water,car,G3,T1
water,tree,GZ,T1
water,tree,GZ,T2
fire,car,GTD,T3
oxygen,bomb,GYYS,T1

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

import csv
from collections import defaultdict


def 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 res


def 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 roll
main()

这是结果中的 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 ;)

关于python - 将 csv 转换为 JSON 树结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43757965/

相关文章:

python - Odoo:服务器操作在列 "activity_user_type"中返回空值违反了非空约束

java - 如何在 Java 的同一测试中模拟具有多个端点的 REST 服务器?

json - 如何读取json格式的数据?

string - Powershell - 从 PsObject 中的 AD 属性获取最后 3 个字符

php - 将 csv 文件上传到 mysql 数据库。 upload.php 文件中的错误

python - 批处理文件可以在 python shell 中执行命令吗?

python 用协方差最小的高斯混合模型(GMM)拟合加权数据

python - 对数组的各个列进行排序

jquery - 使用 jQuery 和 JSON 的动态 Youtube 视频

javascript - 使用 JavaScript 将 HTML 表导出到 CSV 时保留前导零