Welcome to json2xml’s documentation!

json2xml

https://img.shields.io/pypi/v/json2xml.svg https://github.com/vinitkumar/json2xml/actions/workflows/pythonpackage.yml/badge.svghttps://img.shields.io/pypi/pyversions/json2xml.svghttps://badge.fury.io/py/json2xml.svgDocumentation Status https://coveralls.io/repos/github/vinitkumar/json2xml/badge.svg?branch=master

Simple Python Library to convert JSON to XML

Update

The dict2xml project has been forked and integrated in the project itself. This helped with cleaning up the code and also doing improvements. The goal is to remove all the dependencies from this project.

Features

It lets you convert json to xml in following ways:

  • from a json string

  • from a json file

  • from an API that emits json data

Usage

The usage is simple:

from json2xml import json2xml
from json2xml.utils import readfromurl, readfromstring, readfromjson

# get the xml from an URL that return json
data = readfromurl("https://coderwall.com/vinitcool76.json")
print(json2xml.Json2xml(data).to_xml())

# get the xml from a json string
data = readfromstring(
    '{"login":"mojombo","id":1,"avatar_url":"https://avatars0.githubusercontent.com/u/1?v=4"}'
)
print(json2xml.Json2xml(data).to_xml())

# get the data from an URL
data = readfromjson("examples/licht.json")
print(json2xml.Json2xml(data).to_xml())

Custom Wrappers and indent

By default, a wrapper all and pretty True is set. However, you can change this easily in your code like this:

from json2xml import json2xml
from json2xml.utils import readfromurl, readfromstring, readfromjson
data = readfromstring(
    '{"login":"mojombo","id":1,"avatar_url":"https://avatars0.githubusercontent.com/u/1?v=4"}'
)
print(json2xml.Json2xml(data, wrapper="all", pretty=True).to_xml())

Outputs this:

<?xml version="1.0" ?>
<all>
  <login type="str">mojombo</login>
  <id type="int">1</id>
  <avatar_url type="str">https://avatars0.githubusercontent.com/u/1?v=4</avatar_url>
</all>

Omit List item

By default, items in an array are wrapped in <item></item>. However, you can change this easily in your code like this:

from json2xml import json2xml
from json2xml.utils import readfromurl, readfromstring, readfromjson
data = readfromstring(
    '{"my_items":[{"my_item":{"id":1} },{"my_item":{"id":2} }]}'
)
print(json2xml.Json2xml(data, item_wrap=False).to_xml())

Outputs this:

<?xml version="1.0" ?>
<all>
  <my_items type="list">
    <my_item>
        <id type="int">1</id>
    </my_item>
    <my_item>
        <id type="int">2</id>
    </my_item>
  </list>
</all>

Optional Attribute Type Support

Now, we can also specify if the output xml needs to have type specified or not. Here is the usage:

from json2xml import json2xml
from json2xml.utils import readfromurl, readfromstring, readfromjson
data = readfromstring(
    '{"login":"mojombo","id":1,"avatar_url":"https://avatars0.githubusercontent.com/u/1?v=4"}'
)
print(json2xml.Json2xml(data, wrapper="all", pretty=True, attr_type=False).to_xml())

Outputs this:

<?xml version="1.0" ?>
<all>
  <login>mojombo</login>
  <id>1</id>
  <avatar_url>https://avatars0.githubusercontent.com/u/1?v=4</avatar_url>
</all>

The methods are simple and easy to use and there are also checks inside of code to exit cleanly in case any of the input(file, string or API URL) returns invalid JSON.

Credits

This package was created with Cookiecutter and the audreyr/cookiecutter-pypackage project template.

Installation

Stable release

To install json2xml, run this command in your terminal:

$ pip install json2xml

This is the preferred method to install json2xml, as it will always install the most recent stable release.

If you don’t have pip installed, this Python installation guide can guide you through the process.

From sources

The sources for json2xml can be downloaded from the Github repo.

You can either clone the public repository:

$ git clone git://github.com/vinitkumar/json2xml

Or download the tarball:

$ curl  -OL https://github.com/vinitkumar/json2xml/tarball/master

Once you have a copy of the source, you can install it with:

$ python setup.py install

Usage

To use json2xml in a project:

import json2xml

json2xml

json2xml package

Submodules

json2xml.dicttoxml module

Converts a Python dictionary or other native data type into a valid XML string.

Supports item (int, float, long, decimal.Decimal, bool, str, unicode, datetime, none and other
number-like objects) and collection (list, set, tuple and dict, as well as iterable and

dict-like objects) data types, with arbitrary nesting for the collections.

Items with a datetime type are converted to ISO format strings. Items with a None type become empty XML elements.

This module works with both Python 2 and 3.

json2xml.dicttoxml.convert(obj, ids, attr_type, item_func, cdata, item_wrap, parent='root')

Routes the elements of an object to the right function to convert them based on their data type

json2xml.dicttoxml.convert_bool(key, val, attr_type, attr={}, cdata=False)

Converts a boolean into an XML element

json2xml.dicttoxml.convert_dict(obj, ids, parent, attr_type, item_func, cdata, item_wrap)

Converts a dict into an XML string.

json2xml.dicttoxml.convert_kv(key, val, attr_type, attr={}, cdata: bool = False)

Converts a number or string into an XML element

json2xml.dicttoxml.convert_list(items, ids, parent, attr_type, item_func, cdata, item_wrap)

Converts a list into an XML string.

json2xml.dicttoxml.convert_none(key, val, attr_type, attr={}, cdata=False)

Converts a null value into an XML element

json2xml.dicttoxml.default_item_func(parent)
json2xml.dicttoxml.dicttoxml(obj, root: bool = True, custom_root='root', ids=False, attr_type=True, item_wrap=True, item_func=<function default_item_func>, cdata=False)

Converts a python object into XML. Arguments: - root specifies whether the output is wrapped in an XML root element

Default is True

  • custom_root allows you to specify a custom root element. Default is ‘root’

  • ids specifies whether elements get unique ids. Default is False

  • attr_type specifies whether elements get a data type attribute. Default is True

  • item_func specifies what function should generate the element name for items in a list. Default is ‘item’

  • item_wrap specifies whether to nest items in array in <item/> Default is True

  • cdata specifies whether string values should be wrapped in CDATA sections. Default is False

json2xml.dicttoxml.escape_xml(s: str) str
json2xml.dicttoxml.get_unique_id(element)

Returns a unique id for a given element

json2xml.dicttoxml.get_xml_type(val)

Returns the data type for the xml type attribute

json2xml.dicttoxml.key_is_valid_xml(key)

Checks that a key is a valid XML name

json2xml.dicttoxml.make_attrstring(attr)

Returns an attribute string in the form key=”val”

json2xml.dicttoxml.make_id(element, start=100000, end=999999)

Returns a random integer

json2xml.dicttoxml.make_valid_xml_name(key, attr: Dict[str, Any])

Tests an XML name and fixes it if invalid

json2xml.dicttoxml.wrap_cdata(s: str) str

Wraps a string into CDATA sections

json2xml.json2xml module

class json2xml.json2xml.Json2xml(data: str, wrapper: str = 'all', root: bool = True, pretty: bool = True, attr_type: bool = True, item_wrap: bool = True)

Bases: object

to_xml() Optional[Any]

Convert to xml using dicttoxml.dicttoxml and then pretty print it.

json2xml.utils module

Utils methods to convert XML data to dict from various sources

exception json2xml.utils.JSONReadError

Bases: Exception

exception json2xml.utils.StringReadError

Bases: Exception

exception json2xml.utils.URLReadError

Bases: Exception

json2xml.utils.readfromjson(filename: str) Dict[str, str]

Reads a json string and emits json string

json2xml.utils.readfromstring(jsondata: str) Dict[str, str]

Loads json from string

json2xml.utils.readfromurl(url: str, params: Optional[Dict[str, str]] = None) Dict[str, str]

Loads json from an URL over the internets

Module contents

Top-level package for json2xml.

Contributing

Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given.

You can contribute in many ways:

Types of Contributions

Report Bugs

Report bugs at https://github.com/vinitkumar/json2xml/issues.

If you are reporting a bug, please include:

  • Your operating system name and version.

  • Any details about your local setup that might be helpful in troubleshooting.

  • Detailed steps to reproduce the bug.

Fix Bugs

Look through the GitHub issues for bugs. Anything tagged with “bug” and “help wanted” is open to whoever wants to implement it.

Implement Features

Look through the GitHub issues for features. Anything tagged with “enhancement” and “help wanted” is open to whoever wants to implement it.

Write Documentation

json2xml could always use more documentation, whether as part of the official json2xml docs, in docstrings, or even on the web in blog posts, articles, and such.

Submit Feedback

The best way to send feedback is to file an issue at https://github.com/vinitkumar/json2xml/issues.

If you are proposing a feature:

  • Explain in detail how it would work.

  • Keep the scope as narrow as possible, to make it easier to implement.

  • Remember that this is a volunteer-driven project, and that contributions are welcome :)

Get Started!

Ready to contribute? Here’s how to set up json2xml for local development.

  1. Fork the json2xml repo on GitHub.

  2. Clone your fork locally:

    $ git clone git@github.com:your_name_here/json2xml.git
    
  3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:

    $ mkvirtualenv json2xml
    $ cd json2xml/
    $ python setup.py develop
    
  4. Create a branch for local development:

    $ git checkout -b name-of-your-bugfix-or-feature
    

    Now you can make your changes locally.

  5. When you’re done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:

    $ flake8 json2xml tests
    $ python setup.py test or py.test
    $ tox
    

    To get flake8 and tox, just pip install them into your virtualenv.

  6. Commit your changes and push your branch to GitHub:

    $ git add .
    $ git commit -m "Your detailed description of your changes."
    $ git push origin name-of-your-bugfix-or-feature
    
  7. Submit a pull request through the GitHub website.

Pull Request Guidelines

Before you submit a pull request, check that it meets these guidelines:

  1. The pull request should include tests.

  2. If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring, and add the feature to the list in README.rst.

  3. The pull request should work for Python 2.7, 3.4, 3.5 and 3.6, and for PyPy. Check https://travis-ci.org/vinitkumar/json2xml/pull_requests and make sure that the tests pass for all supported Python versions.

Tips

To run a subset of tests:

$ python -m unittest tests.test_json2xml

Deploying

A reminder for the maintainers on how to deploy. Make sure all your changes are committed (including an entry in HISTORY.rst). Then run:

$ bumpversion patch # possible: major / minor / patch
$ git push
$ git push --tags

Travis will then deploy to PyPI if tests pass.

Credits

Development Lead

Contributors

None yet. Why not be the first?

History

v3.8.0 / 2021-10-07

  • Feat/security improvements (#81)

  • arrow_up

    feat: python 3.10 released (#79)

v3.7.0 / 2021-09-11

  • bookmark

    feat: final release for v3.7.0

  • bookmark

    feat: bump version

v3.7.0beta2 / 2021-09-10

  • Feat/cleanup and deprecation fix (#78)

  • item ommision (#76)

  • Create FUNDING.yml

v3.7.0beta1 / 2021-08-28

  • Feat/fork and update dict2xml (#75)

  • chore(deps-dev): bump pip from 18.1 to 19.2 (#73)

  • Delete .travis.yml

  • chore(deps-dev): bump lxml from 4.6.2 to 4.6.3 (#68)

  • Bump lxml from 4.1.1 to 4.6.2 (#66)

v3.6.0 / 2020-11-12

  • Feat/wip exceptions (#65)

  • Add .deepsource.toml

  • feat: upgrade the actions

  • feat: try & support more os and python versions

  • Update pythonpackage.yml

v3.5.0 / 2020-08-24

  • feat: remove six as dependency as we are python3 only, resolves #60 (#61)

  • feat: update makefile for the correct command

v3.4.1 / 2020-06-10

  • fix: issues with pypi release and bump version

  • Feat/attr type docs (#58)

  • fix: conflicts

  • Feat/attr type docs (#57)

  • Merge github.com:vinitkumar/json2xml

  • Update json2xml.py (#56)

  • Merge github.com:vinitkumar/json2xml

  • feat: fix typo in the readme

v3.3.3 / 2020-02-05

  • Update README.rst

  • fix: issue with pypi uploads

  • fix: version

  • bump version

  • Update pythonpackage.yml

  • Refactor/prospector cleanup (#50)

  • Update pythonpackage.yml

  • Create pythonpackage.yml

  • Update README.rst

  • fix: typo in readme

  • bump version

  • Feature/attribute support (#48)

  • Feature/attribute support (#47)

  • chore: bump version

  • fix: remove print statement in json read because it confuses people

  • fix typo in readme

v3.0.0 / 2019-02-26

  • Fix/coveralls (#43)

  • update coverage report (#42)

  • Merge pull request #41 from vinitkumar/fix/coveralls

  • add python coveralls

  • Merge pull request #40 from vinitkumar/refactor/cookiecutter

  • update coverage

  • add image for coveralls

  • coverage and coveralls integrations

  • try and trigger coveralls too

  • fix code block in readme

  • add doc about custom wrapper

  • try at reducing the dependencies

  • add tests for custom wrappers as well

  • add tests for actualy dict2xml conversion

  • fix: remove missing import

  • fix: code syntax highlight in the readme again

  • fix: code syntax highlight in the readme again

  • fix: code syntax highlight in the readme

  • chore: update readme with code samples

  • test: add testcases for the different utils method

  • remove unused imports

  • check the third method for generating dict from json string too

  • run correct test files

  • fix tests

  • update requirements and setuptools

  • refactor the module into more maintainable code

  • chore: add boilerplate

  • remove all legacy

  • Fix/cleanup (#38)

  • cleanup: remove unused modules (#37)

  • Merge pull request #35 from vinitkumar/improve-structure

  • cleanup

  • one again try to get the build working

  • travis need full version for latest supported python

  • do not hardcode version in a series

  • update grammar

  • fix conflicts

  • Update LICENSE

  • cleanup readme

  • remove cli

  • some cleanup and update the tests

  • Update readme.md

  • Cleanup Readme.md

  • Update issue templates

  • fix vulnerabilities in requests

Indices and tables