CSV to JSON script

2024/10/3 14:28:50

I took this script from here:

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

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

But I tried

print out

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 '}]

But when I try to run it as a script, it doesn't work, I get the same error message.

Can anyone help fix the error?

(And is it outputting valid json?)

Thanks

Edit

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.

Answer

Change the nested for loop to:

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

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).

https://en.xdnf.cn/q/70715.html

Related Q&A

Accessing an ALREADY running process, with Python

Question: Is there a way, using Python, to access the stdout of a running process? This process has not been started by Python.Context: There is a program called mayabatch, that renders out images fro…

sum up two pandas dataframes with different indexes element by element

I have two pandas dataframes, say df1 and df2, of some size each but with different indexes and I would like to sum up the two dataframes element by element. I provide you an easy example to better und…

Urwid: make cursor invisible

Im using urwid, which is a Python "framework" for designing terminal user interfaces in ncurses. Theres one thing though that Im not able to do in urwid that was easy in curses - make the cur…

How do I use scipy.weave.inline together with external C libraries?

I am trying to understand weave.inline to wrap C code in my Python programs. The code below simply takes the Numpy array and multiplicates all of its elements by 2.inl.py import numpy import scipy.weav…

sqlalchemy multiple foreign keys to same table

I have a postgres database that looks something like this:Table "public.entities"Column | Type | Modifiers ---------------+---…

Django - Return a file from Root folder via a URL

I purchased a SSL cert online and now ind the mid of verifying my host. How it works is:It gives me a file I have to make that file accessible through a specific URL on my host. If the content of the f…

Flask deployement on lighttpd and raspberry pi

Im trying to deploy a hello flask app to a raspberry pi using lighttpd fastCGI.I followed the instructions on the http://flask.pocoo.org/docs/0.10/deploying/fastcgi/ to the best of my abilityHere is my…

Django admin asks for login after every click

Im working on a Django app hosted on Heroku. Im able to login to the admin with my username, password. But on every single click (or on each click after a few seconds) it redirects me to the login page…

Change numerical Data to Categorical Data - Pandas [duplicate]

This question already has answers here:How to create new values in a pandas dataframe column based on values from another column(2 answers)Closed 6 years ago.I have a pandas dataframe which has a numer…

Why is dataclasses.astuple returning a deepcopy of class attributes?

In the code below the astuple function is carrying out a deep copy of a class attribute of the dataclass. Why is it not producing the same result as the function my_tuple? import copy import dataclass…