python requests xml to json

Converting XML to JSON using Python Requests Library

If you are working with XML data in your Python code and you need to convert it to JSON format, you can easily achieve this using the Requests library. The Requests library makes it easy to send HTTP requests and handle the response data, including converting data between different formats.

Step 1: Install the Requests Library

If you haven't already, you will need to install the Requests library using pip. Open your command prompt or terminal and type:


pip install requests

Step 2: Send a GET Request and Convert the Response to JSON

Now that the Requests library is installed, you can use it to send a GET request to a URL that returns XML data, and then convert the response to JSON format.


import requests
import xmltodict
import json

url = 'https://www.example.com/data.xml'

response = requests.get(url)
xml_data = response.content

json_data = json.dumps(xmltodict.parse(xml_data))
print(json_data)

In the above code, we first import the necessary libraries: Requests, xmltodict, and json. We then define the URL that returns XML data and send a GET request using the Requests library. We get the content of the response using the `content` attribute of the response object.

We then use the `xmltodict.parse()` function to convert the XML data to a Python dictionary, and then use the `json.dumps()` function to convert the dictionary to JSON format. Finally, we print the JSON data.

Alternative Method: Using ElementTree

Another way to convert XML to JSON in Python is to use the ElementTree library:


import requests
import xml.etree.ElementTree as ET
import json

url = 'https://www.example.com/data.xml'

response = requests.get(url)
xml_data = response.content

root = ET.fromstring(xml_data)
json_data = json.dumps(root, indent=4)

print(json_data)

In the above code, we import the necessary libraries: Requests, ElementTree, and json. We then define the URL that returns XML data and send a GET request using the Requests library. We get the content of the response using the `content` attribute of the response object.

We then use the `ET.fromstring()` function to parse the XML data into an ElementTree object, and then use the `json.dumps()` function to convert the ElementTree object to JSON format. Finally, we print the JSON data.