Python Forum
Unable to convert XML to JSON - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Web Scraping & Web Development (https://python-forum.io/forum-13.html)
+--- Thread: Unable to convert XML to JSON (/thread-11226.html)



Unable to convert XML to JSON - priyanka - Jun-29-2018

I have tried to convert a Url link which contains XML file to JSON but unable to do it.
import urllib2
import json
import xmltodict

response.xml = urllib2.urlopen('https://www.openhub.net/projects.xml?api_key=xxxxxxx')


with open("response.xml",'r') as f:
	xmlString = f.read()
jsonString = json.dumps(xmltodict.parse(xmlString), indent=4)
print(jsonString)
This is the code I have used. I am getting the following error.
Error:
import module error:No module named 'urllib2'



RE: Unable to convert XML to JSON - snippsat - Jun-29-2018

You probably use Python 3 as you should Wink
There also a problem,most also write the xml file before read it.
import urllib.request
import json
import xmltodict

xml = urllib.request.urlopen('https://www.openhub.net/projects.xml?api_key=xxxxxxxxxxxxxx')
with open("response.xml", 'wb') as f_out:
    f_out.write(xml.read())  

with open("response.xml", 'r') as f:
	xmlString = f.read()
jsonString = json.dumps(xmltodict.parse(xmlString), indent=4)
print(jsonString)
Ideally don't use urllib at all,but Requests.
import requests
import json
import xmltodict

xml = requests.get('https://www.openhub.net/projects.xml?api_key=xxxxxxxxxxxxxx')
with open("response.xml", 'wb') as f_out:
    f_out.write(xml.content)

with open("response.xml", 'r') as f:
	xmlString = f.read()
jsonString = json.dumps(xmltodict.parse(xmlString), indent=4)
print(jsonString)