The Wayback Machine - https://web.archive.org/web/20241005015750/https://www.geeksforgeeks.org/convert-multiple-json-files-to-csv-python/
Open In App

Convert multiple JSON files to CSV Python

Last Updated : 24 Nov, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will learn how to convert multiple JSON files to CSV file in Python. Before that just recall some terms :

  • JSON File:  A JSON file may be a file that stores simple data structures and objects in JavaScript Object Notation (JSON) format, which may be a standard data interchange format. It is primarily used for transmitting data between an internet application and a server.
  • CSV File:  A CSV may be a comma-separated values file, which allows data to be saved during a tabular format. CSVs appear as if a garden-variety spreadsheet but with a .CSV extension. CSV files are often used with almost any spreadsheet program, like Microsoft Excel or Google Spreadsheets.

To form a CSV file from multiple JSON files, we have to use nested json file, flatten the dataframe or to load the json files into the form of dataframe, concatenate/merge/join these to form one dataframe (at least one column should be same in all json files) and at last convert this dataframe into CSV file. This full procedure of the given task can be understood with the help of examples which are given below :

Example 1:  If all columns match

In this example, we will load two json files, concatenate one to another and convert to a CSV file. The json files used for this are :

file1.json

{
    "ID":{
        "0":23,
        "1":43,
        "2":12,
        "3":13,
        "4":67,
        "5":89
        },
    "Name":{
        "0":"Ram",
        "1":"Deep",
        "2":"Yash",
        "3":"Aman",
        "4":"Arjun",
        "5":"Aditya"
        },
    "Marks":{
        "0":89,
        "1":97,
        "2":45,
        "3":78,
        "4":56,
        "5":76
        },
    "Grade":{
        "0":"B",
        "1":"A",
        "2":"F",
        "3":"C",
        "4":"E",
        "5":"C"
        }
}

file2.json

{
    "ID":{
        "0":90,
        "1":56,
        "2":34,
        "3":96,
        "4":45
         },
    "Name":{
        "0":"Akash",
        "1":"Chalsea",
        "2":"Divya",
        "3":"Sajal",
        "4":"Shubham"
        },
    "Marks":{
        "0":81,
        "1":87,
        "2":100,
        "3":89,
        "4":78
        },
    "Grade":{
        "0":"B",
        "1":"B",
        "2":"A",
        "3":"B",
        "4":"C"
        }
}

Step 1: Load the json files with the help of pandas dataframe.
Step 2 : Concatenate the dataframes into one dataframe.
Step 3: Convert the concatenated dataframe into CSV file.

The complete code with the result is shown below :

Code: 

Python3




# importing packages
import pandas as pd
 
# load json file using pandas
df1 = pd.read_json('file1.json')
 
# view data
print(df1)
 
# load json file using pandas
df2 = pd.read_json('file2.json')
 
# view data
print(df2)
 
# use pandas.concat method
df = pd.concat([df1,df2])
 
# view the concatenated dataframe
print(df)
 
# convert dataframe to csv file
df.to_csv("CSV.csv",index=False)
 
# load the resultant csv file
result = pd.read_csv("CSV.csv")
 
# and view the data
print(result)


Output:

   ID    Name  Marks Grade
0  23     Ram     89     B
1  43    Deep     97     A
2  12    Yash     45     F
3  13    Aman     78     C
4  67   Arjun     56     E
5  89  Aditya     76     C

   ID     Name  Marks Grade
0  90    Akash     81     B
1  56  Chalsea     87     B
2  34    Divya    100     A
3  96    Sajal     89     B
4  45  Shubham     78     C

   ID     Name  Marks Grade
0  23      Ram     89     B
1  43     Deep     97     A
2  12     Yash     45     F
3  13     Aman     78     C
4  67    Arjun     56     E
5  89   Aditya     76     C
0  90    Akash     81     B
1  56  Chalsea     87     B
2  34    Divya    100     A
3  96    Sajal     89     B
4  45  Shubham     78     C

    ID     Name  Marks Grade
0   23      Ram     89     B
1   43     Deep     97     A
2   12     Yash     45     F
3   13     Aman     78     C
4   67    Arjun     56     E
5   89   Aditya     76     C
6   90    Akash     81     B
7   56  Chalsea     87     B
8   34    Divya    100     A
9   96    Sajal     89     B
10  45  Shubham     78     C

Example 2: If some columns match 

In this example, we will load two json files, merge these and convert to a CSV file. The json files used for this are :

file3.json

{
    "ID":{
        "0":23,
        "1":43,
        "2":12,
        "3":13,
        "4":67,
        "5":89
        },
    "Name":{
        "0":"Ram",
        "1":"Deep",
        "2":"Yash",
        "3":"Aman",
        "4":"Arjun",
        "5":"Aditya"
        },
    "Marks":{
        "0":89,
        "1":97,
        "2":45,
        "3":78,
        "4":56,
        "5":76
        }
}

file4.json

{
    "ID":{
        "0":23,
        "1":43,
        "2":12,
        "3":67,
        "4":89
        },
    "Name":{
        "0":"Ram",
        "1":"Deep",
        "2":"Yash",
        "3":"Arjun",
        "4":"Aditya"
        },
    "Grade":{
        "0":"B",
        "1":"A",
        "2":"F",
        "3":"E",
        "4":"C"
        }
}

Step 1: Load the json files with the help of pandas dataframe.

Step 2: Merge the dataframes by different methods as inner/outer/left/right joins.

Step 3: Convert the merged dataframe into CSV file.

The complete code with the result is shown below :

Code:

Python3




# importing packages
import pandas as pd
 
# load json file using pandas
df1 = pd.read_json('file3.json')
 
# view data
print(df1)
 
# load json file using pandas
df2 = pd.read_json('file4.json')
 
# view data
print(df2)
 
# use pandas.merge method
df_inner = pd.merge(df1, df2, how='inner', left_on=[
                    'ID', 'Name'], right_on=['ID', 'Name'])
df_outer = pd.merge(df1, df2, how='outer', left_on=[
                    'ID', 'Name'], right_on=['ID', 'Name'])
df_left = pd.merge(df1, df2, how='left', left_on=[
                   'ID', 'Name'], right_on=['ID', 'Name'])
df_right = pd.merge(df1, df2, how='right', left_on=[
                    'ID', 'Name'], right_on=['ID', 'Name'])
 
# convert dataframe to csv file
df_inner.to_csv("CSV_inner.csv", index=False)
df_outer.to_csv("CSV_outer.csv", index=False)
df_left.to_csv("CSV_left.csv", index=False)
df_right.to_csv("CSV_right.csv", index=False)
 
# load the resultant csv file
result_inner = pd.read_csv("CSV_inner.csv")
result_outer = pd.read_csv("CSV_outer.csv")
result_left = pd.read_csv("CSV_left.csv")
result_right = pd.read_csv("CSV_right.csv")
 
# and view the data
print(result_outer)
print(result_inner)
print(result_left)
print(result_right)


Output:

   ID    Name  Marks
0  23     Ram     89
1  43    Deep     97
2  12    Yash     45
3  13    Aman     78
4  67   Arjun     56
5  89  Aditya     76

   ID    Name Grade
0  23     Ram     B
1  43    Deep     A
2  12    Yash     F
3  67   Arjun     E
4  89  Aditya     C

   ID    Name  Marks Grade
0  23     Ram     89     B
1  43    Deep     97     A
2  12    Yash     45     F
3  13    Aman     78   NaN
4  67   Arjun     56     E
5  89  Aditya     76     C

   ID    Name  Marks Grade
0  23     Ram     89     B
1  43    Deep     97     A
2  12    Yash     45     F
3  67   Arjun     56     E
4  89  Aditya     76     C

   ID    Name  Marks Grade
0  23     Ram     89     B
1  43    Deep     97     A
2  12    Yash     45     F
3  13    Aman     78   NaN
4  67   Arjun     56     E
5  89  Aditya     76     C

   ID    Name  Marks Grade
0  23     Ram     89     B
1  43    Deep     97     A
2  12    Yash     45     F
3  67   Arjun     56     E
4  89  Aditya     76     C

Example 3:  If nested json file is given 

In this example, we will load nested json file, flatten it and then convert into CSV file. The json file used for this is :

file5.json

{
  "tickets":[
    {
      "Name": "Liam",
      "Location": {
        "City": "Los Angeles",
        "State": "CA"
      },
      "hobbies": [
        "Piano",
        "Sports"
      ],
      "year" : 1985,
      "teamId" : "ATL",
      "playerId" : "barkele01",
      "salary" : 870000
    },
    {
      "Name": "John",
      "Location": {
        "City": "Los Angeles",
        "State": "CA"
      },
      "hobbies": [
        "Music",
        "Running"
      ],
      "year" : 1985,
      "teamId" : "ATL",
      "playerId" : "bedrost01",
      "salary" : 550000
    }
  ],
  "count": 2
}

Step 1: Load the nested json file with the help of json.load() method.

Step 2: Flatten the different column values using pandas methods.

Step 3:  Convert the flattened dataframe into CSV file.

Repeat the above steps for both the nested files and then follow either example 1 or example 2 for conversion. To convert a single nested json file follow the method given below.

The complete code with the result is shown below :

Code:

Python3




# importing packages
import pandas as pd
import json
 
# load json file using json.load
with open('file5.json') as file:
    data = json.load(file)
 
# view data
print(data)
 
# form the dataframe
df = pd.DataFrame(data['tickets'])
 
# view dataframe
print(df)
 
# flatten the dataframe and remove unnecessary columns
for i, item in enumerate(df['Location']):
    df['location_city'] = dict(df['Location'])[i]['City']
    df['location_state'] = dict(df['Location'])[i]['State']
 
for i, item in enumerate(df['hobbies']):
    df['hobbies_{}'.format(i)] = dict(df['hobbies'])[i]
 
df = df.drop({'Location', 'hobbies'}, axis=1)
 
# view dataframe
print(df)
 
# convert dataframe to csv file
df.to_csv("CSV.csv", index=False)
 
# load the resultant csv file
result = pd.read_csv("CSV.csv")
 
# and view the data
print(result)


Output:

{‘tickets’: [{‘Name’: ‘Liam’, ‘Location’: {‘City’: ‘Los Angeles’, ‘State’: ‘CA’}, ‘hobbies’: [‘Piano’, ‘Sports’], ‘year’: 1985, ‘teamId’: ‘ATL’, ‘playerId’: ‘barkele01’, ‘salary’: 870000}, {‘Name’: ‘John’, ‘Location’: {‘City’: ‘Los Angeles’, ‘State’: ‘CA’}, ‘hobbies’: [‘Music’, ‘Running’], ‘year’: 1985, ‘teamId’: ‘ATL’, ‘playerId’: ‘bedrost01’, ‘salary’: 550000}], ‘count’: 2}

                                Location  Name                  hobbies   playerId  \

0  {‘City’: ‘Los Angeles’, ‘State’: ‘CA’}  Liam   [Piano, Sports]  barkele01   

1  {‘City’: ‘Los Angeles’, ‘State’: ‘CA’}  John  [Music, Running]  bedrost01    

    salary teamId  year  

0  870000    ATL  1985  

1  550000    ATL  1985    

    Name   playerId  salary teamId  year location_city location_state  \

0  Liam  barkele01  870000    ATL  1985   Los Angeles             CA   

1  John  bedrost01  550000    ATL  1985   Los Angeles             CA   

      hobbies_0 hobbies_1  

0     Piano     Music  

1    Sports   Running     

    Name   playerId  salary teamId  year location_city location_state  \

0  Liam  barkele01  870000    ATL  1985   Los Angeles             CA   

1  John  bedrost01  550000    ATL  1985   Los Angeles             CA    

     hobbies_0 hobbies_1  

0     Piano     Music  

1    Sports   Running  



Previous Article
Next Article

Similar Reads

How to create multiple CSV files from existing CSV file using Pandas ?
In this article, we will learn how to create multiple CSV files from existing CSV file using Pandas. When we enter our code into production, we will need to deal with editing our data files. Due to the large size of the data file, we will encounter more problems, so we divided this file into some small files based on some criteria like splitting in
3 min read
Read multiple CSV files into separate DataFrames in Python
Sometimes you might need to read multiple CSV files into separate Pandas DataFrames. Importing CSV files into DataFrames helps you work on the data using Python functionalities for data analysis. In this article, we will see how to read multiple CSV files into separate DataFrames. For reading only one CSV file, we can use pd.read_csv() function of
2 min read
How to Merge multiple CSV Files into a single Pandas dataframe ?
While working with CSV files during data analysis, we often have to deal with large datasets. Sometimes, it might be possible that a single CSV file doesn't consist of all the data that you need. In such cases, there's a need to merge these files into a single data frame. Luckily, the Pandas library provides us with various methods such as merge, c
3 min read
Convert JSON to CSV in Python
The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-
3 min read
Convert nested JSON to CSV in Python
In this article, we will discuss how can we convert nested JSON to CSV in Python. An example of a simple JSON file: As you can see in the example, a single key-value pair is separated by a colon (:) whereas each key-value pairs are separated by a comma (,). Here, "name", "profile", "age", and "location" are the key fields while the corresponding va
9 min read
Convert CSV to JSON using Python
CSV (or Comma Separated Value) files represent data in a tabular format, with several rows and columns. An example of a CSV file can be an Excel Spreadsheet. These files have the extension of .csv, for instance, geeksforgeeks.csv. In this sample file, every row will represent a record of the dataset, and each column will indicate a unique feature v
2 min read
How to merge multiple excel files into a single files with Python ?
Normally, we're working with Excel files, and we surely have come across a scenario where we need to merge multiple Excel files into one. The traditional method has always been using a VBA code inside excel which does the job but is a multi-step process and is not so easy to understand. Another method is manually copying long Excel files into one w
4 min read
Reading and Writing CSV Files in Python
CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. It is one of the most common methods for exchanging data between applications and popular data format used in Data Science. It is supported by a wide range of applications. A CSV file stores tabular data in which each data field is separa
4 min read
How to merge two csv files by specific column using Pandas in Python?
In this article, we are going to discuss how to merge two CSV files there is a function in pandas library pandas.merge(). Merging means nothing but combining two datasets together into one based on common attributes or column. Syntax: pandas.merge() Parameters : data1, data2: Dataframes used for merging.how: {‘left’, ‘right’, ‘outer’, ‘inner’}, def
3 min read
How to read numbers in CSV files in Python?
Prerequisites: Reading and Writing data in CSV, Creating CSV files CSV is a Comma-Separated Values file, which allows plain-text data to be saved in a tabular format. These files are stored in our system with a .csv extension. CSV files differ from other spreadsheet file types (like Microsoft Excel) because we can only have a single sheet in a file
4 min read
Getting all CSV files from a directory using Python
Python provides many inbuilt packages and modules to work with CSV files in the workspace. The CSV files can be accessed within a system's directories and subdirectories and modified or edited. The CSV file contents can both be printed on the shell, or it can be saved in the form of the dataframe and played with later. In this article, we will see
3 min read
Working with large CSV files in Python
Data plays a key role in building machine learning and the AI model. In today's world where data is being generated at an astronomical rate by every computing device and sensor, it is important to handle huge volumes of data correctly. One of the most common ways of storing data is in the form of Comma-Separated Values(CSV). Directly importing a la
4 min read
Reading CSV files in Python
A CSV (Comma Separated Values) file is a form of plain text document that uses a particular format to organize tabular information. CSV file format is a bounded text document that uses a comma to distinguish the values. Every row in the document is a data log. Each log is composed of one or more fields, divided by commas. It is the most popular fil
5 min read
Writing CSV files in Python
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as spreadsheets or databases. Each line of the file represents a data record, with fields separated by commas. This format is popular due to its simplicity and wide support. Ways to Write CSV Files in PythonBelow are the ways by which we can write CSV files in Pyt
11 min read
Working with csv files in Python
Python is one of the important fields for data scientists and many programmers to handle a variety of data. CSV (Comma-Separated Values) is one of the prevalent and accessible file formats for storing and exchanging tabular data. In article explains What is CSV. Working with CSV files in Python, Reading, and Writing to a CSV file, and Storing Email
10 min read
Saving Text, JSON, and CSV to a File in Python
Python allows users to handle files (read, write, save and delete files and many more). Because of Python, it is very easy for us to save multiple file formats. Python has in-built functions to save multiple file formats. Opening a text file in Python Opening a file refers to getting the file ready either for reading or for writing. This can be don
5 min read
Concatenating CSV files using Pandas module
Using pandas we can perform various operations on CSV files such as appending, updating, concatenating, etc. In this article, we are going to concatenate two CSV files using pandas module. Suppose we have one .csv file named Employee.csv which contains some records and it is as below: There is another .csv file named Updated.csv which contains new
3 min read
How to read all CSV files in a folder in Pandas?
In this article, we will see how to read all CSV files in a folder into single Pandas dataframe. The task can be performed by first finding all CSV files in a particular folder using glob() method and then reading the file by using pandas.read_csv() method and then displaying the content. Approach:Import necessary python packages like pandas, glob,
1 min read
How to import and export data using CSV files in PostgreSQL
In this article, we are going to see how to import and export data using CSV file in PostgreSQL, the data in CSV files can be easily imported and exported using PostgreSQL. To create a CSV file, open any text editor (notepad, vim, atom). Write the column names in the first line. Add row values separated by commas to the corresponding columns in the
3 min read
How to Read CSV Files with NumPy?
In this article, we will discuss how to read CSV files with Numpy in Python. Reading CSV files using Python NumPy library helps in loading large amount of data quicker. Due to performance reason, NumPy is preferred while reading huge amount of data from CSV files. Dataset in use: Read CSV Files using built-in Python open() function Here we are not
3 min read
Creating a dataframe using CSV files
CSV files are the “comma-separated values”, these values are separated by commas, this file can be viewed like an excel file. In Python, Pandas is the most important library coming to data science. We need to deal with huge datasets while analyzing the data, which usually can get in CSV file format. Creating a pandas data frame using CSV files can
2 min read
Saving scraped items to JSON and CSV file using Scrapy
In this article, we will see how to use crawling with Scrapy, and, Exporting data to JSON and CSV format. We will scrape data from a webpage, using a Scrapy spider, and export the same to two different file formats. Here we will extract from the link http://quotes.toscrape.com/tag/friendship/. This website is provided by the makers of Scrapy, for l
5 min read
How to Sort CSV by multiple columns in Python ?
In this article, we are going to discuss how to sort a CSV file by multiple columns. First, we will convert the CSV file into a data frame then we will sort the data frame by using the sort_values() method. Syntax: DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind=’quicksort’, na_position=’last’) Return Type: Returns a sorted Da
2 min read
Python - Difference between json.dump() and json.dumps()
JSON is a lightweight data format for data interchange which can be easily read and written by humans, easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. Note: For more information, refer to Working With JSON Data in Python json.dumps() json.
2 min read
Python - Difference Between json.load() and json.loads()
JSON (JavaScript Object Notation) is a script (executable) file which is made of text in a programming language, is used to store and transfer the data. It is a language-independent format and is very easy to understand since it is self-describing in nature. Python has a built-in package called json. In this article, we are going to see Json.load a
3 min read
json.loads() vs json.loads() in Python
orjson.loads() and json.loads() are both Python methods used to deserialize (convert from a string representation to a Python object) JSON data. orjson and json are both Python libraries that provide functions for encoding and decoding JSON data. However, they have some differences in terms of performance and compatibility. json is a built-in Pytho
4 min read
Convert CSV to Excel using Pandas in Python
Pandas can read, filter, and re-arrange small and large datasets and output them in a range of formats including Excel. In this article, we will be dealing with the conversion of .csv file into excel (.xlsx). Pandas provide the ExcelWriter class for writing data frame objects to excel sheets. Syntax: final = pd.ExcelWriter('GFG.xlsx') Example:Sampl
1 min read
Convert CSV to HTML Table in Python
CSV file is a Comma Separated Value file that uses a comma to separate values. It is basically used for exchanging data between different applications. In this, individual rows are separated by a newline. Fields of data in each row are delimited with a comma.Example : Name, Salary, Age, No.of years employed Akriti, 90000, 20, 1 Shreya, 100000, 21,
2 min read
Convert HTML table into CSV file in python
CSV file is a Comma Separated Value file that uses a comma to separate values. CSV file is a useful thing in today's world when we are talking about machine learning, data handling, and data visualization. In this article, we will discuss how to convert an HTML table into a CSV file. Converting HTML Table into CSV file in Python Example: Suppose HT
2 min read
Convert Excel to CSV in Python
In this article, we will be dealing with the conversion of Excel (.xlsx) file into .csv. There are two formats mostly used in Excel : (*.xlsx) : Excel Microsoft Office Open XML Format Spreadsheet file.(*.xls) : Excel Spreadsheet (Excel 97-2003 workbook). Let's Consider a dataset of a shopping store having data about Customer Serial Number, Customer
3 min read
Practice Tags :