top of page
horizontal lines
Gigasheet Primary logo
  • Syed Hasan

How to Convert JSON to CSV in Python

Most web systems and APIs now send out responses in the JSON data format. Though the format itself is quite easy to read and write, perhaps you’d like to work with CSVs? Converting JSON to CSV using Python or other techniques can get daunting fairly quickly.


There are two ways to solve the problem:

  1. You can use a language like Python and code the conversion using libraries like Pandas.

  2. If you’re not fond of coding, we’ve got a much easier route. You can use Gigasheet.

In this article, we’ll walk through you through both ways to convert JSON to CSV, using Python code as well as the the #NoCode way of converting JSON to CSV.

Convert JSON to CSV

Convert JSON to CSV in Python

Python is extremely handy for developers, data analysts, and several other roles. It can be used for operations ranging from automating #DataConversion operations (like the one we’re going to talk about) to performing complex scientific calculations. Truly wonderful!


However, it does require you to code. Coding requires both experience and a lot of time – which in your case you might not have.


For instance, if you’d like to convert JSON to CSV in Python, you can use functions from the Pandas library. It has two functions, namely read_json and to_csv which can read JSON and convert to CSV in a few seconds.


Here’s sample code using the aforementioned functions for converting a very basic JSON structure to a CSV sheet:


import pandas as pd

jsonBody = pd.read_json("sample.json")

csvBody = jsonBody.to_csv()


The csvBody variable contains the CSV data which we can now print out. Here’s the console output containing both the JSON and CSV bodies:


Console output of JSON and CSV files

How simple? Only thing is; the JSON in the sample.json file is a simple list of a single object with no nested objects i.e., a simple structure which is rarely the case with production systems. Here’s the content of the file:


[{

"A": 1,

"B": 2,

"C": "ABC",

}]


Now, what happens when you’d like to convert a complex JSON to a CSV? This is where you’ll be spending some time debugging issues with your data, normalizing or flattening objects, and more – requiring more time!


Python’s Pandas does have a function to normalize the JSON from a semi-structured dataset to a flattened object (with no nestings, easier for CSV conversion).


I’ve updated the sample.json file to contain a few more objects with nesting thereby creating a bit more complex JSON structure:


[{

"a": 1,

"b": {

"c": "OK",

"d": 0

},

"e": {

"f": {

"g": "NOT OK"

}

}

},