Skip to content

Instantly share code, notes, and snippets.

@gamesbook
Created September 2, 2017 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gamesbook/7fc0c365f202b8b8676a6db5fd2e7dc2 to your computer and use it in GitHub Desktop.
Save gamesbook/7fc0c365f202b8b8676a6db5fd2e7dc2 to your computer and use it in GitHub Desktop.
Show creating XML (with optional elements) from nested JSON via jinja2 templating
# -*- coding: utf-8 -*-
"""Purpose: Show creating XML from nested JSON with optional elements.
Created: 2017-09-03
Author: dhohls@csir.co.za
"""
from __future__ import print_function
from jinja2 import Template
xml_template = """<?xml version="1.0" encoding="UTF-8"?>
<urlset>{% for val in values %}
<person>
<name>{{val.name}}</name>
<surname>{{val.surname}}</surname>
<age>{{val.age}}</age>
{% if val.contact %}<contact>
<email>{{val.contact.email}}</email>
<phone>{{val.contact.phone}}</phone>
</contact>{% endif %}
</person>{% endfor %}
</urlset>"""
# JSON-like
values = [
{
"name": "John",
"surname": "Brown",
"age": 25,
"contact": {
"email": "foo",
"phone": "011"
}
},
{
"name": "Jane",
"surname": "Smith",
"age": 19
}
]
t = Template(xml_template)
print(t.render(values=values))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment