How to convert CSV to JSON in Python
The process of file format conversion Python is definitely no cake walk, especially for CSV to JSON. So how can we add this important functionality to a project while protecting our afternoon from being wasted on the task? Well, I have just the thing.
We start off by pip installing our API client:
pip install cloudmersive-convert-api-client
And with a simple function call for convert_data_csv_to_json, involving an API instance, we may proceed thus:
from __future__ import print_functionimport timeimport cloudmersive_convert_api_clientfrom cloudmersive_convert_api_client.rest import ApiExceptionfrom pprint import pprint# Configure API key authorization: Apikeyconfiguration = cloudmersive_convert_api_client.Configuration()configuration.api_key['Apikey'] = 'YOUR_API_KEY'# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed# configuration.api_key_prefix['Apikey'] = 'Bearer'# create an instance of the API classapi_instance = cloudmersive_convert_api_client.ConvertDataApi(cloudmersive_convert_api_client.ApiClient(configuration))input_file = '/path/to/file' # 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 conversionapi_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)
And now all you need to do is specify your input file path. Once it has your request, the API will make the appropriate format conversions and then return your JSON file. Now that’s a cake walk!