0

If I use this script to convert from Json to Csv in Python:

import json

import csv

with open("data.json") as file:
    data = json.loads(file)

with open("data.csv", "w") as file:
    csv_file = csv.writer(file)
    for item in data:
        csv_file.writerow([item['studio'], item['title']] +    item['release_dates'].values())

It throws an error message:

Traceback (most recent call last):

File "<stdin>", line 2, in <module>

File "C:\Python27\lib\json\__init__.py", line 338, in loads
    return _default_decoder.decode(s)

File "C:\Python27\lib\json\decoder.py", line 365, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Blank
  • 81
  • 11
  • 1
    Try `data = json.load(file)` instead of `data = json.loads(file)`. `loads` is meant for a string. – Akavall Oct 25 '15 at 02:05

1 Answers1

1

You're using json.loads() when you should be using json.load().

json.loads is for reading from a string, whereas json.load is for reading from a file.

Visit here for more information: https://docs.python.org/2/library/json.html.

Also, unrelated, but you can chain with statements.

with open("data.json") as json_file, open("data.csv", "w") as csv_file:
    csv_file = csv.writer(csv_file)
    for item in json.load(json_file):
        csv_file.writerow(...)
dursk
  • 4,435
  • 2
  • 19
  • 30
  • Traceback (most recent call last): File "", line 1, in IOError: [Errno 2] No such file or directory: 'data.json' I get this error if I make that change. – Blank Oct 25 '15 at 02:08
  • That error looks like it's happening on the `open()` line, not the `json.load` line. – dursk Oct 25 '15 at 02:11
  • It is not able to find the location of the file. I have kept the file in the python folder inside the program files. Still unable to access. Not sure why this is happening. – Blank Oct 25 '15 at 02:20
  • Traceback (most recent call last): File "", line 3, in File"C:\Users\dell\AppData\Local\Programs\Python\Python27\lib\json\__init__.py", line 268, in load parse_constant=parse_constant,object_pairs_hook=object_pairs_hook, **kw) File"C:\Users\dell\AppData\Local\Programs\Python\Python27\lib\json\__init__.py", line 319, in loads return _default_decoder.decode(s) File"C:\Users\dell\AppData\Local\Programs\Python\Python27\lib\json\decoder.py", line 342, in decode raise JSONDecodeError("Extra data", s, end) json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 2065) – Blank Oct 25 '15 at 02:23