Reputation: 283
I have a text file where each line is a different JSON array with the same set of keys but different values in each line. Each line is formatted like so:
{"Key A":"Value A1","Key B":"Value B1","Key C":"Value C1, Value C2, Value C3"}
I want to pull the values of one key and the first 4 values of another key and export to a csv file.
I want the output to look like this:
Value A1 ["Value C1", "Value C2", "Value C3"]
Value A12 ["Value C12", "Value C22", "Value C32"]
So far, I've split the file into multiple lines like this:
import json
import csv
jsonmov = []
with open('step3_desired_output.txt') as step3:
for line in step3:
jsonmov.append(json.loads(line))
print jsonmov{u'Title',[u'Actors'[0:3]]} #print each line from jsonmov's title and 4 actors
This gives me an error:
TypeError: list indices must be integers, not tuple
Another syntax for the print line:
print jsonmov(u'Title',u'Actors')
gives the error
TypeError: 'list' object is not callable:
Any ideas on how to produce the csv file in the right format?
Upvotes: 0
Views: 118
Reputation: 104102
Do you mean something like:
import json
import csv
with open('/tmp/test.json') as f, open('/tmp/jout.csv', 'w') as fout:
writer=csv.writer(fout)
for line in f:
jline=json.loads(line)
print jline[u'Key A']+'\t['+jline[u'Key C']+']'
# Value A1 [Value C1, Value C2, Value C3]
# write to writer...
Edit
Perhaps:
import json
with open('/tmp/test.json') as f, open('/tmp/jout.csv', 'w') as fout:
for line in f:
data=[]
jline=json.loads(line)
print jline[u'Key A']+'\t['+', '.join('"{}"'.format(e.strip()) for e in jline[u'Key C'].split(','))+']'
# Value A1 ["Value C1", "Value C2", "Value C3"]
# add '\n' if you print to a file...
Upvotes: 1
Reputation: 56714
import json
import csv
INPUT = 'step3_desired_output.txt'
OUTPUT = 'my.csv'
MAXACTORS = 3
with open(OUTPUT, 'wb') as outf:
outcsv = csv.writer(outf)
with open(INPUT) as inf:
for line in inf:
mv = json.loads(line)
title = mv['Title']
actors = mv['Actors'].split(', ', MAXACTORS)
outcsv.writerow([title] + actors[:MAXACTORS])
Upvotes: 1