How to Convert CSV to JSON in Python

Cloudmersive
2 min readFeb 17, 2021

The Comma Separated Value (CSV) format is designed to simplify exporting data from one program and importing it into another program. While CSV is ideal for some tasks due to its compact nature, its lack of versatility occasionally makes it difficult to manage in others. The following API can facilitate the conversion of a CSV file to the more scalable and online-friendly JSON format.

The first step of the process is to install the client:

pip install cloudmersive-convert-api-client

Next we will call the function with the following code:

from __future__ import print_function
import time
import cloudmersive_convert_api_client
from cloudmersive_convert_api_client.rest import ApiException
from pprint import pprint
# Configure API key authorization: Apikey
configuration = cloudmersive_convert_api_client.Configuration()
configuration.api_key['Apikey'] = 'YOUR_API_KEY'
# create an instance of the API class
api_instance = cloudmersive_convert_api_client.ConvertDataApi(cloudmersive_convert_api_client.ApiClient(configuration))
input_file = '/path/to/inputfile' # file | Input file to perform the operation on.
column_names_from_first_row = true # bool | Optional; If true, the first row will be used as the labels for the columns; if false, columns will be named Column0, Column1, etc. Default is true. Set to false if you are not using column headings, or have an irregular column structure. (optional)
try:
# Convert CSV to JSON conversion
api_response = api_instance.convert_data_csv_to_json(input_file, column_names_from_first_row=column_names_from_first_row)
pprint(api_response)
except ApiException as e:
print("Exception when calling ConvertDataApi->convert_data_csv_to_json: %s\n" % e)

To ensure the process runs smoothly, be sure to input your API key and your ColumnNamestoFirstRow field; the default for the latter input is true, so you will have to set it to false if you are not using column headings.

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.