3

尝试根据此示例从 csv 创建一个 4 深嵌套 JSON:

Region,Company,Department,Expense,Cost
Gondwanaland,Bobs Bits,Operations,nuts,332
Gondwanaland,Bobs Bits,Operations,bolts,254
Gondwanaland,Maureens Melons,Operations,nuts,123

在每个级别,我想汇总成本并将其包含在相关级别的输出 JSON 中。

输出的 JSON 的结构应如下所示:

    {
          "id": "aUniqueIdentifier", 
          "name": "usually a nodes name", 
          "data": [
                {
                      "key": "some key", 
                      "value": "some value"
                }, 
                {
                      "key": "some other key", 
                      "value": "some other value"
                }
          ], 
          "children": [/* other nodes or empty */ ]
    }

(参考:http ://blog.thejit.org/2008/04/27/feeding-json-tree-structures-to-the-jit/ )

沿着 python 中的递归函数的思路思考,但到目前为止,这种方法并没有取得太大的成功......任何关于快速简便的解决方案的建议非常感谢?

更新:逐渐放弃汇总成本的想法,因为我无法弄清楚:(。我还不是一个 python 编码器)!仅仅能够生成格式化的 JSON 就足够了,如果需要,我可以稍后插入数字。

一直在阅读、搜索和阅读解决方案,并且在途中学到了很多东西,但仍然没有成功从上述 CSV 结构创建我的嵌套 JSON 文件。必须是网络上某个地方的简单解决方案?也许其他人的搜索词更幸运????

4

1 回答 1

8

这里有一些提示。

使用csv.reader将输入解析为列表列表:

>>> rows = list(csv.reader(source.splitlines()))

循环遍历列表以建立您的字典并总结成本。根据您要创建的结构,构建可能如下所示:

>>> summary = []
>>> for region, company, department, expense, cost in rows[1:]:
    summary.setdefault(*region, company, department), []).append((expense, cost))

json.dump写出结果:

>>> json.dump(summary, open('dest.json', 'wb'))

希望下面的递归函数可以帮助您入门。它从输入构建一棵树。请注意您希望叶子的类型,我们将其标记为“成本”。您需要详细说明该功能以构建您想要的确切结构:

import csv, itertools, json

def cluster(rows):
    result = []
    for key, group in itertools.groupby(rows, key=lambda r: r[0]):
        group_rows = [row[1:] for row in group]
        if len(group_rows[0]) == 2:
            result.append({key: dict(group_rows)})
        else:
            result.append({key: cluster(group_rows)})
    return result

if __name__ == '__main__':
    s = '''\
Gondwanaland,Bobs Bits,Operations,nuts,332
Gondwanaland,Bobs Bits,Operations,bolts,254
Gondwanaland,Maureens Melons,Operations,nuts,123
'''
    rows = list(csv.reader(s.splitlines()))
    r = cluster(rows)
    print json.dumps(r, indent=4)
于 2011-10-31T00:06:11.637 回答