将 JSON 转换为 CSV
在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试这样的事情。
# 现在你已经有了 json 到 csv 文件的格式,你可以使用 awk;
...
try something like this.
# Now you have your json to csv file for formatting you can use awk;
...
如:
为每行创建一个主键(PK)。
在 Car 和 Person 之间创建外键 (FK) 关系。看来 Car 对 Person 具有“依赖”关系。
步骤 1. 对 JSON 对象使用
enumerate
。这将为每个人提供方便的 PK。步骤 2. 使用每个人的方便 PK 作为您创建的每辆车的 FK。
唯一令人不快的事情是将 PK 分配给汽车,因为没有方便的方法在您的特定数据结构上使用
enumerate
。为此,您必须使用一个好的旧计数器。http://docs.python.org/library/functions.html#enumerate
As in:
Create a Primary Key (PK) for each row.
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
我刚刚发布了一个模块,可以在 Node.js 中简化此过程
https://www.npmjs.com/package /json导出
I just released a module that makes this process easy in Node.js
https://www.npmjs.com/package/jsonexport