-3

Here is my file_t.JSON am writing from Request content to a csv/json file

{"w1":"R"}
{"w2":"R2"}
{"w3":"R3"}
{"w4":"R4"}
{"w5":"R5"}

I'm expecting that my code below should give me the below result Expecting output.csv

w1 r
w2 R2
w3 R3
W4 R4
w5 R5

Here is my code

import csv

f1 = file ("output.csv","w")

f2 = file ("file_t.JSON","rU")

with open("file_t.JSON") as f:
    csvr = csv.reader(f, delimiter=' ')
    csvr.next()
    for rec in csvr:
        key, values_txt = rec
        values = values_txt.split(',')
        print key, values
        f1.write(values)

It is not printing, writing to the output file.

  • That isn't valid JSON. Is that example supposed to represent multiple JSON documents, one per line? Or is it just a typo that there are no commas between objects? – DavidO Mar 05 '17 at 07:10
  • Your code actually has bug, this is what I got by running your code: Traceback (most recent call last): File "csv_test.py", line 11, in key, values_txt = rec ValueError: need more than 1 value to unpack The variable *rec* is a array consists of only one element, which is the entire line of your json file. You can refer to @mhawke's answer for the right solution. – zhou Mar 05 '17 at 07:17

1 Answers1

2

Read the JSON file line by line and convert each line to a Python dictionary using json.loads(). Then write that out to the CSV file:

import csv
import json

with open("file_t.JSON") as infile, open('output.csv', 'w') as outfile:
    writer = csv.writer(outfile, delimiter=' ')
    for line in infile:
        d = json.loads(line)
        writer.writerows(d.items())
mhawke
  • 84,695
  • 9
  • 117
  • 138
  • How to write the same in col1 and col2, instead of writing them in col1 only?? – code drill Mar 06 '17 at 01:03
  • They are in column 1 and column 2 if you treat _space_ as the field delimiter (as does your example). If you want a different delimiter specify that when you instantiate the `csv.writer`, or you can omit it if you want a comma. – mhawke Mar 06 '17 at 08:29