简体   繁体   中英

Decoding a JSON text file in python

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM