Home:ALL Converter>Extract json fields and write them into a csv with python

Extract json fields and write them into a csv with python

Ask Time:2016-06-08T18:17:53         Author:Lara M.

Json Formatter

I've got a very big json with multiple fields and I want to extract just some of them and then write them into a csv.

Here is my code:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import json

import csv

data_file = open("book_data.json", "r")
values = json.load(data_file)
data_file.close()

with open("book_data.csv", "wb") as f:
    wr = csv.writer(f)
    for data in values:
         value = data["identifier"]
         value = data["authors"]
         for key, value in data.iteritems():
               wr.writerow([key, value])

It gives me this error:

File "json_to_csv.py", line 22, in <module>
wr.writerow([key, value])
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 8: ordinal not in range(128)

But I give the utf-8 encoding on the top, so I don't know what's wrong there.

Thanks

Author:Lara M.,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/37699691/extract-json-fields-and-write-them-into-a-csv-with-python
yy