How to Convert JSON to XML in Python
Let’s walk through a simple solution we can use to convert our JSON data to XML files in Python using minimal code.
We’ll be converting our JSON data to XML through a free API using the complementary Python code examples provided below.
We can begin by installing the client SDK with pip install:
pip install cloudmersive-convert-api-client
Next, we can turn our attention to API call authorization. We’ll need a free Cloudmersive API key to authorize our requests (this will allow up to 800 API calls per month with zero commitments).
With our API key ready, we can add the imports and copy the JSON to XML function into our file. Our JSON object goes in the json_object
request variable:
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))
json_object = NULL # object | Input JSON Object to convert to XML
try:
# Convert JSON Object to XML conversion
api_response = api_instance.convert_data_json_to_xml(json_object)
pprint(api_response)
except ApiException as e:
print("Exception when calling ConvertDataApi->convert_data_json_to_xml: %s\n" % e)
If we want to convert a JSON string to XML instead of an object, we can call the below function instead. Our JSON string goes in the json_string
request variable:
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))
json_string = 'json_string_example' # str | Input JSON String to convert to XML
try:
# Convert JSON String to XML conversion
api_response = api_instance.convert_data_json_string_to_xml(json_string)
pprint(api_response)
except ApiException as e:
print("Exception when calling ConvertDataApi->convert_data_json_string_to_xml: %s\n" % e)
Just like that, we can now easily and make JSON to XML conversions using two distinct low-code API methods.