简体   繁体   中英

Convert nested JSON to CSV in Python

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"]])

您正在使用wb+将文件打开为二进制文件,而您正在尝试写str

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM