如何转换csv到层次json [英] How to convert csv to hierarchial json

查看:721
本文介绍了如何转换csv到层次json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个csv文件,其格式为:

I have a csv file which is of the form:

Category Sub-Category Value
 A            A1        1
 A            A2        2
 A            A3        5
 B            B1        10
 B            B2        3
 C            C1        2
 C            C2        2
 C            C3        3
 D            D1        5



我需要将其转换为json(等级)来做一些d3。 js可视化。所以,我需要得到这个形式

I need to convert it into json (hierarchial) to do some d3.js visualization. So, I need to get this in the form

{
 "name": "AllData",
 "children": [
  {
   "Category": "A",
     "children": [
      {"Sub-Category": "A1", "Value": 1},
      {"Sub-Category": "A2", "Value": 2},
      {"Sub-Category": "A3", "Value": 5}]...

我该如何做?我不是很熟悉javascript。

How do I go about doing this? I'm not very well versed in javascript. I'd prefer something in python.

推荐答案

这将工作

import json
f = open('path/to/file','r')
arr=[]
headers = []

for header in f.readline().split(','):
headers.append(header)



for line in f.readlines():
lineItems = {}

for i,item in enumerate(line.split(',')):  
lineItems[headers[i]] = item


arr.append(lineItems)

f.close()

jsonText = json.dumps(arr)

print jsonText

来源

这篇关于如何转换csv到层次json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆