tags:

views:

1360

answers:

5

i have a json file and i want to covert to .csv file but with python how to do this. sorry i new in using python

0 vote down check

i have try

import json 

import csv

f = open('data.json') 

data = json.load(f) 

f.close()

f = open('data.csv') 

csv_file = csv.writer(f) 

for item in data: 

f.writerow(item) 

f.close()

but it not work

i use django and error like this

file' object has no attribute 'writerow'

and after that i try

import json 

import csv

f = open('data.json') 

data = json.load(f) 

f.close()

f = open('data.csv') 

csv_file = csv.writer(f) 

for item in data: 

csv_file.writerow(item) 

f.close()

and this error again

the error is

sequence expected

[ { "pk": 22, "model": "auth.permission", "fields": { "codename": "add_logentry", "name": "Can add log entry", "content_type": 8 } }, { "pk": 23, "model": "auth.permission", "fields": { "codename": "change_logentry", "name": "Can change log entry", "content_type": 8 } }, { "pk": 24, "model": "auth.permission", "fields": { "codename": "delete_logentry", "name": "Can delete log entry", "content_type": 8 } }, { "pk": 4, "model": "auth.permission", "fields": { "codename": "add_group", "name": "Can add group", "content_type": 2 } }, { "pk": 10, "model": "auth.permission", "fields": { "codename": "add_message", "name": "Can add message", "content_type": 4 } }, ]

+3  A: 

Python has a JSON module and a CSV module as part of its standard library. You should be able to read the appropriate documentation and build the converter you need.

Trent
+2  A: 

This code should work for you, assuming that your json data is in a file called data.json.

import json
import csv

f = open('data.json')
data = json.load(f)
f.close()

f = open('data.csv')
csv_file = csv.writer(f)
for item in data:
  f.writerow([item['pk'], item['model']] + item['fields'].values())
f.close()
Dan Loewenherz
Hmmm, no -- `csv_file.writerow` (there is no `f.writerow` of course, I assume you made a typo there!) wants a sequence, not a dict -- and in your example, each item is a dict. This would work for the OTHER special case, as I identified in my answer - where the JSON file has an array of arrays; it doesn't work for an array of objects, which is the special case you appear to be trying to solve (that one requires a `csv.DictWriter` -- and of course you need to extract the field names and decide on an order in order to instantiate it!-).
Alex Martelli
Oops, typo. Thanks for catching that.
Dan Loewenherz
+3  A: 

JSON can represent a wide variety of data structures -- a JS "object" is roughly like a Python dict (with string keys), a JS "array" roughly like a Python list, and you can nest them as long as the final "leaf" elements are numbers or strings.

CSV can essentially represent only a 2-D table -- optionally with a first row of "headers", i.e., "column names", which can make the table interpretable as a list of dicts, instead of the normal interpretation, a list of lists (again, "leaf" elements can be numbers or strings).

So, in the general case, you can't translate an arbitrary JSON structure to a CSV. In a few special cases you can (array of arrays with no further nesting; arrays of objects which all have exactly the same keys). Which special case, if any, applies to your problem? The details of the solution depend on which special case you do have. Given the astonishing fact that you don't even mention which one applies, I suspect you may not have considered the constraint, neither usable case in fact applies, and your problem is impossible to solve. But please do clarify!

Alex Martelli
A: 

i have try

import json import csv

f = open('data.json') data = json.load(f) f.close()

f = open('data.csv') csv_file = csv.writer(f) for item in data: f.writerow(item) f.close()

but it not work

i use django and error like this

file' object has no attribute 'writerow'

little_fish
This is the sort of information that should be in the question, not in an answer. Also, you can format code so it's more readable by putting four spaces in the front of each line.
Suppressingfire
That should at least be csv_file.writerow() as seen in this pydoc: http://docs.python.org/library/csv.html#writer-objects
Suppressingfire
My mistake--it should have been `csv_file.writerow()`.
Dan Loewenherz
i have try but it error agin the error issequence expected
little_fish
+2  A: 

I am not sure this question is solved already or not, but let me paste what I have done for reference.

First, your JSON has nested objects, so its normally cannot do direct convertion to csv. You need to change that to something like this

[{ 
"pk": 22, "model": "auth.permission", "codename": "add_logentry", "name": "Can add log entry", "content_type": 8 
},
......]

Here is my code to generate csv from that

import json
import csv

x="""[ 
    { "pk": 22, "model": "auth.permission", "fields": 
        { "codename": "add_logentry", "name": "Can add log entry", "content_type": 8 } 
    }, 
    { "pk": 23, "model": "auth.permission", "fields": 
        { "codename": "change_logentry", "name": "Can change log entry", "content_type": 8 } 
    },
    { "pk": 24, "model": "auth.permission", "fields": 
        { "codename": "delete_logentry", "name": "Can delete log entry", "content_type": 8 } 
    }
]"""

x=json.loads(x)

f=csv.writer(open("test.csv","wb+"))

# Write CSV Header, If you dont need that, remove this line
f.writerow(["pk","model","codename","name","content_type"])

for x in x:
    f.writerow([x["pk"], x["model"], 
    x["fields"]["codename"],x["fields"]["name"],x["fields"]["content_type"]])

You will get output as

pk,model,codename,name,content_type
22,auth.permission,add_logentry,Can add log entry,8
23,auth.permission,change_logentry,Can change log entry,8
24,auth.permission,delete_logentry,Can delete log entry,8
S.Mark
this is work but sorry before can i get something that not hard codei thing it better id i can use f.writerow(a)and the a is some variabel that i declare before thanks before
little_fish