CSV到JSON脚本 [英] CSV to JSON script

查看:141
本文介绍了CSV到JSON脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从这里取得这个指令码:

import csv
from itertools import izip
f = open( '/django/sw2/wkw2/csvtest1.csv', 'r' )
reader = csv.reader( f )
keys = ( "firm_url", "firm_name", "first", "last", "school", "year_graduated" )
out = []
for property in reader:
    property = iter( property )
    data = {}
    for key in keys:
        data[ key ] = property.next()
    out += [ data ]
print out

尝试它在IDLE我得到错误

When I tried it in IDLE I got the error

Traceback (most recent call last):
  File "<pyshell#13>", line 5, in <module>
    data [key] = property.next()
StopIteration

尝试

print out


b $ b

再次打印

again and then it printed

[{'school': 'The George Washington University Law School', 'last': 'Abbas', 'firm_url': 'http://www.whitecase.com/aabbas', 'year_graduated': ' 2005', 'firm_name': 'White & Case', 'first': ' Amr A '}, {'school': 'Ernst Moritz Arndt University Greifswald', 'last': 'Adam', 'firm_url': 'http://www.whitecase.com/kadam', 'year_graduated': ' 2004', 'firm_name': 'White & Case', 'first': ' Karin '}, {'school': 'Tashkent State Law Institute', 'last': 'Adjivefayev', 'firm_url': 'http://www.whitecase.com/vadjivefayev', 'year_graduated': ' 2002', 'firm_name': 'White & Case', 'first': ' Vilen '}]

但是当我试图运行它

任何人都可以帮助解决这个错误?

Can anyone help fix the error?

感谢

感谢您的答案。似乎这不是将csv文件转换为json格式的正确方法。我只是试图转换csv文件中的数据,以便我可以使用 loaddata 填充我的sqlite3数据库在django。在django组中查看此主题: http://groups.google.com/ group / django-users / browse_frm / thread / a00b529ba2147d91 我尝试使用csv2json.py snippet。和另一个线程今天在操作系统(对不起,我不能包括2个链接)。我会欣赏一个简单的方法将csv转换为json。或者你用来填充我应该使用的django数据库的方法。感谢您的帮助。

Thanks for the answers. It seems that this is not the right way of converting a csv file to json format. I am just trying to convert the csv file with data in it so that I can use loaddata to populate my sqlite3 database in django. See this thread in django group: http://groups.google.com/group/django-users/browse_frm/thread/a00b529ba2147d91 for my attempt to use csv2json.py snippet. And another thread today in OS (Sorry I cannot include 2 links). I would appreciate a simple way of converting csv to json. Or the method you use to populate your django database that I should be using instead. Thanks for the help.

推荐答案

out = [dict(zip(keys, property)) for property in reader]

并且,不,打印输出将不会发出有效的JSON - 使用 print json.dumps(out)(你还需要 import json 当然是一个Python 2.6标准库模块但你可以找到版本工作与2.5如果这是你需要的)。

and, no, print out will not emit valid JSON -- use print json.dumps(out) (you'll need to import json too of course -- that's a Python 2.6 standard library module but you can find versions working with 2.5 if that's what you need).

这篇关于CSV到JSON脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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