【问题标题】:Convert csv to JSON tree structure and change name?将 csv 转换为 JSON 树结构并更改名称?
【发布时间】:2018-11-14 10:07:54
【问题描述】:

感谢 Hatt 的解释和代码。它有效,尽管我无法从列标题中更改字符串 name 以获得有意义的名称。

谁能建议如何实现这一目标?

csv 文件中的数据

conversion_month    channel sub_channel campaign    Id  cost    kpi
2017-08 DISPLAY Retargeting Summer_Campaign 200278217   2.286261    0.1
2017-08 DISPLAY Retargeting Summer_Campaign 200278218   3.627064    2.5
2017-08 DISPLAY Retargeting Summer_Campaign 200278219   2.768436    0.001
2017-08 DISPLAY Retargeting August Campaign 200278220   5.653297    0.35
2017-09 DISPLAY Prospecting Test Campaign   200278221   4.11847 1.5
2017-08 DISPLAY Prospecting August Campaign 200278222   3.393972    0.26
2017-09 DISPLAY Prospecting Test Campaign   200278223   3.975332    4.2
2017-08 DISPLAY Prospecting August Campaign 200278224   4.131035    0.3

使用的代码:

import csv
from collections import defaultdict

def ctree():
    return defaultdict(ctree)

def build_leaf(name, leaf):
    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():
    tree = ctree()
    with open('file.csv') as csvfile:
        reader = csv.reader(csvfile)
        for rid, row in enumerate(reader):
            if rid == 0:       
                continue
            leaf = tree[row[0]]
            for cid in range(1, (len(row)-2)):
                leaf = leaf[row[cid]]
            for cid in range((len(row)-1), len(row)):
                leaf = (leaf[row[cid-1]],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, indent=2))

main()

它给出了树,但我想将字符串“name”更改为有意义的名称,例如“month”、“channel”、...“id”等。名称在第一行.csv 文件。

[
  {
    "name": "2017-08",
    "children": [
      {
        "name": "DISPLAY",
        "children": [
          {
            "name": "Retargeting",
            "children": [
              {
                "name": "Summer_Campaign",
                "children": [
                  {
                    "name": "200278217",
                    "children": [
                      {
                        "name": "2.286261"
                      },
                      {
                        "name": "0.1"
                      }
                    ]

提前感谢您的任何建议。

【问题讨论】:

标签: python json csv tree


【解决方案1】:

使用next(reader) 首先从 CSV 文件中提取标题行。 level 计数器可用于指示当前正在处理哪一列,因此可以从表头中提取相应的列表头:

import csv
from collections import defaultdict

def ctree():
    return defaultdict(ctree)

def build_leaf(name, leaf, level, header):
    res = {header[level] : name}
    # add children node if the leaf actually has any children
    if len(leaf.keys()) > 0:
        res["children"] = [build_leaf(k, v, level+1, header) for k, v in leaf.items()]
    return res

def main():
    tree = ctree()
    with open('file.csv') as csvfile:
        reader = csv.reader(csvfile)
        header = next(reader)

        for row in reader:
            leaf = tree[row[0]]
            for cid in range(1, (len(row)-2)):
                leaf = leaf[row[cid]]
            for cid in range((len(row)-1), len(row)):
                leaf = (leaf[row[cid-1]],leaf[row[cid]])

    # building a custom tree structure
    res = []
    for name, leaf in tree.items():
        res.append(build_leaf(name, leaf, 0, header))

    # printing results into the terminal
    import json
    print(json.dumps(res, indent=2))

main()

这会给你:

[
  {
    "conversion_month": "2017-08",
    "children": [
      {
        "channel": "DISPLAY",
        "children": [
          {
            "sub_channel": "Retargeting",
            "children": [
              {
                "campaign": "Summer_Campaign",
                "children": [
                  {
                    "Id": "200278217",
                    "children": [
                      {
                        "cost": "2.286261"
                      },

【讨论】:

  • 谢谢马丁!
猜你喜欢
  • 2017-10-01
  • 1970-01-01
  • 2020-01-16
  • 2021-08-07
  • 1970-01-01
  • 1970-01-01
  • 2022-07-15
  • 2011-06-10
  • 1970-01-01
相关资源
最近更新 更多