将 JSON 转换为 CSV

发布于 2024-09-28 06:00:37 字数 597 浏览 1 评论 0原文

在 python 中,我有一个由列表和字典组成的复杂对象层次结构。我想将其全部导出为 CSV 或某种其他类型的数据库格式。非常感谢任何 Python 或 Javascript 的答案。

据我了解,一个 CSV 文件(或表)只能代表层次结构中的一个“级别”对象,因此解决方案需要创建多个文件。

这是一个例子:

{
    "Person" : [{"name":"Greg","age":"35","car":["honda civic","ford focus"]},
                {"name":"Steve","age":"28", "car":["mazda 323", "toyota camry"]}]
}

基本上

Person.csv:
id,name,age
1,Greg,35
2,Steve,28

car.csv:
id,Person_id,value
1,1,honda civic
2,1,ford focus
3,2,mazda 323
4,2,toyota camry

,这里唯一有趣的事情是分配新的 id,以便表中的行可以关联起来。

干杯, 戴夫

In python I have a complex object hierarchy made of lists and dictionaries. I want to spit it all out to CSV or some other kind of database format. Any answers in Python or Javascript very much appreciated.

I understand that one CSV file (or table) can only represent one 'level' of object in my hierarchy, so the solution would need to create multiple files.

Here is an example:

{
    "Person" : [{"name":"Greg","age":"35","car":["honda civic","ford focus"]},
                {"name":"Steve","age":"28", "car":["mazda 323", "toyota camry"]}]
}

would become

Person.csv:
id,name,age
1,Greg,35
2,Steve,28

car.csv:
id,Person_id,value
1,1,honda civic
2,1,ford focus
3,2,mazda 323
4,2,toyota camry

Basically the only thing interesting going on here is the assignment of new ids so that the rows in the tables can be associated.

Cheers,
Dave

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

灰色世界里的红玫瑰 2024-10-05 06:00:37

尝试这样的事情。

json_dict = {
    "Person" : [{"name":"Greg","age":"35","car":["honda civic","ford focus"]},
                {"name":"Steve","age":"28", "car":["mazda 323", "toyota camry"]}]
}

for entity in json_dict:
    csv_file = open('%s.csv' % entity, 'wb')
    headers = a[entity][0].keys()
    csv_writer = csv.DictWriter(csv_file, headers)
    map(csv_writer.writerow, json_dict[entity])
    csv_file.close()

# 现在你已经有了 json 到 csv 文件的格式,你可以使用 awk;

awk  -F , '{print NR ", " $2 ", " $3 }' Person.csv > person.csv

...

try something like this.

json_dict = {
    "Person" : [{"name":"Greg","age":"35","car":["honda civic","ford focus"]},
                {"name":"Steve","age":"28", "car":["mazda 323", "toyota camry"]}]
}

for entity in json_dict:
    csv_file = open('%s.csv' % entity, 'wb')
    headers = a[entity][0].keys()
    csv_writer = csv.DictWriter(csv_file, headers)
    map(csv_writer.writerow, json_dict[entity])
    csv_file.close()

# Now you have your json to csv file for formatting you can use awk;

awk  -F , '{print NR ", " $2 ", " $3 }' Person.csv > person.csv

...

你的往事 2024-10-05 06:00:37

分配新的 ID,以便可以关联表中的行。

如:

  1. 为每行创建一个主键(PK)。

  2. 在 Car 和 Person 之间创建外键 (FK) 关系。看来 Car 对 Person 具有“依赖”关系。

步骤 1. 对 JSON 对象使用 enumerate。这将为每个人提供方便的 PK。

步骤 2. 使用每个人的方便 PK 作为您创建的每辆车的 FK。

唯一令人不快的事情是将 PK 分配给汽车,因为没有方便的方法在您的特定数据结构上使用enumerate。为此,您必须使用一个好的旧计数器。

http://docs.python.org/library/functions.html#enumerate

assignment of new ids so that the rows in the tables can be associated.

As in:

  1. Create a Primary Key (PK) for each row.

  2. Create a Foreign Key (FK) relationship between Car and Person. It appears that Car has a "dependent" relationship on Person.

Step 1. Use enumerate on your JSON objects. This will give you a handy PK for each Person.

Step 2. Use the handy PK for each Person as the FK for each Car you create.

The only thing that's unpleasant is assigning PK's to the Cars since there's no handy way to use enumerate on your particular data structure. For that, you have to use a good old counter.

http://docs.python.org/library/functions.html#enumerate

紙鸢 2024-10-05 06:00:37
import json
import csv
temp = json.load(open('filename.json','r'))
output =[]
for each in temp:
     row = {}
     row['field1'] =each['field1']
     row['field2'] = each['field2']
     output.append(row)
file = open( "filename_destination.csv", "w")

fileWriter = csv.writer(file , delimiter=",",quotechar='"', quoting=csv.QUOTE_MINIMAL)

Header = ['field1','field2']

fileWriter.writerow(Header)

for x in output:
te = [x['field1'],x['field2']]
fileWriter.writerow(te)
file.close()
import json
import csv
temp = json.load(open('filename.json','r'))
output =[]
for each in temp:
     row = {}
     row['field1'] =each['field1']
     row['field2'] = each['field2']
     output.append(row)
file = open( "filename_destination.csv", "w")

fileWriter = csv.writer(file , delimiter=",",quotechar='"', quoting=csv.QUOTE_MINIMAL)

Header = ['field1','field2']

fileWriter.writerow(Header)

for x in output:
te = [x['field1'],x['field2']]
fileWriter.writerow(te)
file.close()
不疑不惑不回忆 2024-10-05 06:00:37

我刚刚发布了一个模块,可以在 Node.js 中简化此过程

var jsonexport = require('jsonexport');

var contacts = [{
   name: 'Bob',
   lastname: 'Smith',
   family: {
       name: 'Peter',
       type: 'Father'
   }
},{
   name: 'James',
   lastname: 'David',
   family:{
       name: 'Julie',
       type: 'Mother'
   }
},{
   name: 'Robert',
   lastname: 'Miller',
   family: null,
   location: [1231,3214,4214]
},{
   name: 'David',
   lastname: 'Martin',
   nickname: 'dmartin'
}];

jsonexport(contacts,function(err, csv){
    if(err) return console.log(err);
    console.log(csv);
});

https://www.npmjs.com/package /json导出

I just released a module that makes this process easy in Node.js

var jsonexport = require('jsonexport');

var contacts = [{
   name: 'Bob',
   lastname: 'Smith',
   family: {
       name: 'Peter',
       type: 'Father'
   }
},{
   name: 'James',
   lastname: 'David',
   family:{
       name: 'Julie',
       type: 'Mother'
   }
},{
   name: 'Robert',
   lastname: 'Miller',
   family: null,
   location: [1231,3214,4214]
},{
   name: 'David',
   lastname: 'Martin',
   nickname: 'dmartin'
}];

jsonexport(contacts,function(err, csv){
    if(err) return console.log(err);
    console.log(csv);
});

https://www.npmjs.com/package/jsonexport

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文