Reputation: 81
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
Upvotes: 0
Views: 439
Reputation: 4445
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(...)
Upvotes: 1