0

I am trying to convert JSON data into a CSV in Python and found this code listed on Stack Exchange from a while back (link:How can I convert JSON to CSV?)

It no longer works in Python 3, giving me different errors. Anyone know how to fix for Python 3? Thanks.

import csv
import json

x = """[
    {
        "pk": 22,
        "model": "auth.permission",
        "fields": {
            "codename": "add_logentry",
            "name": "Can add log entry",
            "content_type": 8
        }
    },
    {
        "pk": 23,
        "model": "auth.permission",
        "fields": {
            "codename": "change_logentry",
            "name": "Can change log entry",
            "content_type": 8
        }
    },
    {
        "pk": 24,
        "model": "auth.permission",
        "fields": {
            "codename": "delete_logentry",
            "name": "Can delete log entry",
            "content_type": 8
    }
    }
]"""

x = json.loads(x)

f = csv.writer(open("test.csv", "wb+"))

# Write CSV Header, If you dont need that, remove this line
f.writerow(["pk", "model", "codename", "name", "content_type"])

for x in x:
    f.writerow([x["pk"],
                x["model"],
                x["fields"]["codename"],
                x["fields"]["name"],
                x["fields"]["content_type"]])
1
  • What are the errors? Commented Nov 24, 2017 at 23:58

2 Answers 2

2

You were opening the file as binary with wb+ whereas you are trying to write str.

f = csv.writer(open("test.csv", "w+"))
Sign up to request clarification or add additional context in comments.

Comments

0

Maybe this code will help you in some way to understand that.

import json,csv    

data = []

with open('your_json_file_here.json') as file:
    for line in file:
        data.append(json.loads(line)) length = len(data)

with open('create_new_file.csv','w') as f:
    writer = csv.writer(f)
    writers = csv.DictWriter(f, fieldnames=['header1','header2'])
    writers.writeheader()
    for iter in range(length):

        writer.writerow((data[iter]['specific_col_name1'],data[iter]['specific_col_name2'])) f.close()

Comments

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.