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
1
  • 1
    Try data = json.load(file) instead of data = json.loads(file). loads is meant for a string. Commented Oct 25, 2015 at 2:05

1 Answer 1

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(...)
Sign up to request clarification or add additional context in comments.

4 Comments

Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: [Errno 2] No such file or directory: 'data.json' I get this error if I make that change.
That error looks like it's happening on the open() line, not the json.load line.
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.
Traceback (most recent call last): File "<stdin>", line 3, in <module> 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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.