Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I have a JSON file that I want to covert to a CSV file. How can I do this with Python?

I tried:

import json

import csv

f = open('data.json')

data = json.load(f)

f.close()

f = open('data.csv')

csv_file = csv.writer(f)

for item in data:

    f.writerow(item)

f.close()

However, it did not work. I am using Django and the error I received is:

file' object has no attribute 'writerow'

So, then I tried the following:

import json

import csv

f = open('data.json')

data = json.load(f)

f.close()

f = open('data.csv')

csv_file = csv.writer(f)

for item in data:

    csv_file.writerow(item)

f.close()

I then get the error:

sequence expected

Sample json file:

[

  {

    "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

    }

  },

  {

    "pk": 4,

    "model": "auth.permission",

    "fields": {

      "codename": "add_group",

      "name": "Can add group",

      "content_type": 2

    }

  }

1 Answer

0 votes
by (25.1k points)

You can do it like this:

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

If you want to get a deeper understanding of python you can watch this youtube video: 

Related questions

0 votes
1 answer
asked Oct 4, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
asked Dec 10, 2020 in Python by laddulakshana (16.4k points)
0 votes
1 answer

Browse Categories

...