2

While converting json file to csv,I got the above error My code is shown below:

import json
import csv
data = open("SRInFlow.json",encoding="utf8")
rows = json.loads(data.read())
r=rows.values()
fieldnames = [b'dateTimeValues', b'timeSeries']
with open('C:/DeepLearning/tensorflowpoc/Codes/SRInFlow.csv', 'w') as f:
    dict_writer = csv.DictWriter(f, fieldnames=fieldnames)
    dict_writer.writeheader()
    for d in r:
  --->    dict_writer.writerow(d)

The error displays in the last line. How to rectify the error? Thanks in advance

Green Falcon
  • 14,308
  • 10
  • 59
  • 98
Sheetal
  • 53
  • 2
  • 3
  • 7

1 Answers1

3

This error is because you are initialising a dictionary writer dict_writer = csv.DictWriter(f, fieldnames=fieldnames) but then you are passing a normal row containing only the values r=rows.values() -> for d in r: ->dict_writer.writerow(d), when the writer expects a dictionary including the keys. That is what the error means.

I don't know how your JSON looks but you can try something like this:

import json
import csv

data = '{"dateTimeValues": [1,3,4], "timeSeries": [0,0,0]}'
rows = json.loads(data)

r=zip(*rows.values())

fieldnames = ['dateTimeValues', 'timeSeries']
with open('c:/Users/jsz.P3-GROUP/Desktop/shit.csv', 'w') as f:
    dict_writer = csv.writer(f)
    dict_writer.writerow(fieldnames)
    for d in r:
        dict_writer.writerow(d)

This initialises a simple csv writer dict_writer = csv.writer(f)(not dictionary), then inputs the fieldnames as a normal row for the header dict_writer.writerow(fieldnames) and finally inserts only the values as in your example.

Note that for my json string I had to transpose the values first as in r=zip(*rows.values()).

Hope this helps.

TitoOrt
  • 1,892
  • 14
  • 23