How to convert XML to JSON in Python

If you are yawning at the very prospect of coding a means to convert between XML and JSON, then well, I can’t really blame you. I have your salvation, however, in the form of an API, one that will perform this conversion for you effortlessly. You just need to set it up with a few lines of code.

Let’s install our API client first; use this command for pip install:

pip install cloudmersive-convert-api-client

Now for calling convert_data_xml_to_json. To do this, we start by stating our API key, creating our API instance, and then providing our function with an input file. See below.

from __future__ import print_functionimport timeimport cloudmersive_convert_api_clientfrom 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.try:# Convert XML to JSON conversionapi_response = api_instance.convert_data_xml_to_json(input_file)pprint(api_response)except ApiException as e:print("Exception when calling ConvertDataApi->convert_data_xml_to_json: %s\n" % e)

And you’re done!

Image for post

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store