April 05, 2021
There are certain cases where you need to serialize some response into JSON but your desired API only offers XML res.
So here’s how you format/convert XML response into JSON.
googling returned few ways to do this but you might want to do it as simple as possible
(i.e. online converters, XML → dict → JSON, … )
xmljson 0.2.0
available JSON conventions
"attributes" for attributes, "children" for nodes"$" for text content, @ to prefix attributes"attributes" for sorted attributes (even when empty), "children" for nodes, values are strings"$t" for text content, attributes added as-is"content" for text content, attributes added as-isXML
<employees>
<person>
<name value="Alice"/>
</person>
<person>
<name value="Bob"/>
</person>
</employees>JSON
{
"employees": [{
"person": {
"name": {
"@value": "Alice"
}
}
}, {
"person": {
"name": {
"@value": "Bob"
}
}
}]
}[example in Python]
pip install xmljsonfrom xmljson import yahoo
key = [API_SPECIFIC_KEY]
url = [API_URL] + key
request = requests.get(url).text
response = json.dumps(yahoo.data(fromstring(request)), ensure_ascii=False)
try:
response = json.loads(response)['response']['body']
except KeyError:
response = {
'status_code': 200,
'results': 'temporarily unavailable',
}
serialized['STRUCTURE_0']['STRUCTURE_1'] = response
serialized = json.dumps(serialized)Reference
https://pypi.org/project/xmljson/