xmljson Documentation

Similar documents
TPS Documentation. Release Thomas Roten

Roman Numeral Converter Documentation

Python wrapper for Viscosity.app Documentation

Python simple arp table reader Documentation

chatterbot-weather Documentation

Python Project Example Documentation

PyCRC Documentation. Release 1.0

Aircrack-ng python bindings Documentation

Simple libtorrent streaming module Documentation

I2C LCD Documentation

sainsmart Documentation

Release Nicholas A. Del Grosso

django-idioticon Documentation

google-search Documentation

Poulpe Documentation. Release Edouard Klein

django-reinhardt Documentation

Simple Binary Search Tree Documentation

DNS Zone Test Documentation

Redis Timeseries Documentation

Frontier Documentation

Pykemon Documentation

Google Domain Shared Contacts Client Documentation

Release Fulfil.IO Inc.

withenv Documentation

Python State Machine Documentation

Django Wordpress API Documentation

django-cas Documentation

smartfilesorter Documentation

Python Schema Generator Documentation

Mantis STIX Importer Documentation

OpenUpgrade Library Documentation

e24paymentpipe Documentation

Game Server Manager Documentation

django CMS Export Objects Documentation

doconv Documentation Release Jacob Mourelos

gunny Documentation Release David Blewett

pydrill Documentation

eventbrite-sdk-python Documentation

pyldavis Documentation

Poetaster. Release 0.1.1

django-users2 Documentation

API Wrapper Documentation

xmodels Documentation

open-helpdesk Documentation

Python State Machine Documentation

dj-libcloud Documentation

ejpiaj Documentation Release Marek Wywiał

Python AMT Tools Documentation

Python AutoTask Web Services Documentation

Release Ralph Offinger

dublincore Documentation

yardstick Documentation

smsghussd Documentation

Aldryn Installer Documentation

Python Finite State Machine. Release 0.1.5

django-telegram-bot Documentation

pvl Documentation Release William Trevor Olson

AnyDo API Python Documentation

Python data pipelines similar to R Documentation

syslog-ng Apache Kafka destination

django-responsive2 Documentation

django-composite-foreignkey Documentation

gpib-ctypes Documentation

dicompyler-core Documentation

lazy-object-proxy Release 1.3.1

Dragon Mapper Documentation

nacelle Documentation

django-composite-foreignkey Documentation

PyCon APAC 2014 Documentation

Airoscript-ng Documentation

PyZillow Documentation

Job Submitter Documentation

Durga Documentation. Release dev2. transcode

OTX to MISP. Release 1.4.2

ProxySQL Tools Documentation

Connexion Sqlalchemy Utils Documentation

Archan. Release 2.0.1

django-stored-messages Documentation

cwmon-mysql Release 0.5.0

django-private-chat Documentation

Gearthonic Documentation

Infoblox Client Documentation

invenio-groups Documentation

CID Documentation. Release Francis Reyes

Microlab Instruments Documentation

Release Manu Phatak

invenio-formatter Documentation

pytest-benchmark Release 2.5.0

django-bootstrap3 Documentation

MyAnimeList Scraper. Release 0.3.0

MT940 Documentation. Release Rick van Hattem (wolph)

redis-lock Release 3.2.0

django-dynamic-db-router Documentation

python-hologram-api Documentation

timegate Documentation

Regressors Documentation

otree Virtual Machine Manager Documentation

Pulp Python Support Documentation

Python Project Documentation

Lazarus Documentation

Transcription:

xmljson Documentation Release 0.1.9 S Anand Aug 01, 2017

Contents 1 About 3 2 Convert data to XML 5 3 Convert XML to data 7 4 Conventions 9 5 Options 11 6 Installation 13 7 Roadmap 15 8 More information 17 8.1 Contributing............................................... 17 8.2 Credits.................................................. 19 8.3 History.................................................. 20 8.4 Indices and tables............................................ 21 i

ii

xmljson converts XML into Python dictionary structures (trees, like in JSON) and vice-versa. Contents 1

2 Contents

CHAPTER 1 About XML can be converted to a data structure (such as JSON) and back. For example: <employees> <person> <name value="alice"/> </person> <person> <name value="bob"/> </person> </employees> can be converted into this data structure (which also a valid JSON object): { } "employees": [{ "person": { "name": { "@value": "Alice" } } }, { "person": { "name": { "@value": "Bob" } } }] This uses the BadgerFish convention that prefixes attributes with @. The conventions supported by this library are: Abdera: Use "attributes" for attributes, "children" for nodes BadgerFish: Use "$" for text content, @ to prefix attributes 3

Cobra: Use "attributes" for sorted attributes (even when empty), "children" for nodes, values are strings GData: Use "$t" for text content, attributes added as-is Parker: Use tail nodes for text content, ignore attributes Yahoo Use "content" for text content, attributes added as-is 4 Chapter 1. About

CHAPTER 2 Convert data to XML To convert from a data structure to XML using the BadgerFish convention: >>> from xmljson import badgerfish as bf >>> bf.etree({'p': {'@id': 'main', '$': 'Hello', 'b': 'bold'}}) This returns an array of etree.element structures. In this case, the result is identical to: >>> from xml.etree.elementtree import fromstring >>> [fromstring('<p id="main">hello<b>bold</b></p>')] The result can be inserted into any existing root etree.element: >>> from xml.etree.elementtree import Element, tostring >>> result = bf.etree({'p': {'@id': 'main'}}, root=element('root')) >>> tostring(result) '<root><p id="main"/></root>' This includes lxml.html as well: >>> from lxml.html import Element, tostring >>> result = bf.etree({'p': {'@id': 'main'}}, root=element('html')) >>> tostring(result, doctype='<!doctype html>') '<!DOCTYPE html>\n<html><p id="main"></p></html>' For ease of use, strings are treated as node text. For example, both the following are the same: >>> bf.etree({'p': {'$': 'paragraph text'}}) >>> bf.etree({'p': 'paragraph text'}) By default, non-string values are converted to strings using Python s str, except for booleans which are converted into true and false (lower case). Override this behaviour using xml_fromstring: >>> tostring(bf.etree({'x': 1.23, 'y': True}, root=element('root'))) '<root><y>true</y><x>1.23</x></root>' >>> from xmljson import BadgerFish # import the class 5

>>> bf_str = BadgerFish(xml_tostring=str) # convert using str() >>> tostring(bf_str.etree({'x': 1.23, 'y': True}, root=element('root'))) '<root><y>true</y><x>1.23</x></root>' 6 Chapter 2. Convert data to XML

CHAPTER 3 Convert XML to data To convert from XML to a data structure using the BadgerFish convention: >>> bf.data(fromstring('<p id="main">hello<b>bold</b></p>')) {"p": {"$": "Hello", "@id": "main", "b": {"$": "bold"}}} To convert this to JSON, use: >>> from json import dumps >>> dumps(bf.data(fromstring('<p id="main">hello<b>bold</b></p>'))) '{"p": {"b": {"$": "bold"}, "@id": "main", "$": "Hello"}}' To preserve the order of attributes and children, specify the dict_type as OrderedDict (or any other dictionarylike type) in the constructor: >>> from collections import OrderedDict >>> from xmljson import BadgerFish # import the class >>> bf = BadgerFish(dict_type=OrderedDict) # pick dict class By default, values are parsed into boolean, int or float where possible (except in the Yahoo method). Override this behaviour using xml_fromstring: >>> dumps(bf.data(fromstring('<x>1</x>'))) '{"x": {"$": 1}}' >>> bf_str = BadgerFish(xml_fromstring=False) # Keep XML values as strings >>> dumps(bf_str.data(fromstring('<x>1</x>'))) '{"x": {"$": "1"}}' >>> bf_str = BadgerFish(xml_fromstring=repr) # Custom string parser '{"x": {"$": "\'1\'"}}' xml_fromstring can be any custom function that takes a string and returns a value. In the example below, only the integer 1 is converted to an integer. Everything else is retained as a float: >>> def convert_only_int(val):... return int(val) if val.isdigit() else val 7

>>> bf_int = BadgerFish(xml_fromstring=convert_only_int) >>> dumps(bf_int.data(fromstring('<p><x>1</x><y>2.5</y><z>nan</z></p>'))) '{"p": {"x": {"$": 1}, "y": {"$": "2.5"}, "z": {"$": "NaN"}}}' 8 Chapter 3. Convert XML to data

CHAPTER 4 Conventions To use a different conversion method, replace BadgerFish with one of the other classes. Currently, these are supported: >>> from xmljson import abdera # == xmljson.abdera() >>> from xmljson import badgerfish # == xmljson.badgerfish() >>> from xmljson import cobra # == xmljson.cobra() >>> from xmljson import gdata # == xmljson.gdata() >>> from xmljson import parker # == xmljson.parker() >>> from xmljson import yahoo # == xmljson.yahoo() 9

10 Chapter 4. Conventions

CHAPTER 5 Options Conventions may support additional options. The Parker convention absorbs the root element by default. parker.data(preserve_root=true) preserves the root instance: >>> from xmljson import parker, Parker >>> from xml.etree.elementtree import fromstring >>> from json import dumps >>> dumps(parker.data(fromstring('<x><a>1</a><b>2</b></x>'))) '{"a": 1, "b": 2}' >>> dumps(parker.data(fromstring('<x><a>1</a><b>2</b></x>'), preserve_root=true)) '{"x": {"a": 1, "b": 2}}' 11

12 Chapter 5. Options

CHAPTER 6 Installation This is a pure-python package built for Python 2.6+ and Python 3.0+. To set up: pip install xmljson 13

14 Chapter 6. Installation

CHAPTER 7 Roadmap Test cases for Unicode Support for namespaces and namespace prefixes 15

16 Chapter 7. Roadmap

CHAPTER 8 More information 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/sanand0/xmljson/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 is open to whoever wants to implement it. Implement Features Look through the GitHub issues for features. Anything tagged with feature is open to whoever wants to implement it. 17

Write Documentation xmljson could always use more documentation, whether as part of the official xmljson 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/sanand0/xmljson/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! xmljson runs on Python 2.6+ and Python 3+ in any OS. To set up the development environment: 1. Fork the xmljson repo 2. Clone your fork locally: git clone git@github.com:your_user_id/xmljson.git 3. Install your local copy into a virtualenv. If you have virtualenvwrapper installed, this is how you set up your fork for local development: $ mkvirtualenv xmljson $ cd xmljson/ $ python setup.py develop 4. Create a branch for local development: git checkout -b <branch-name> Now you can make your changes locally. 5. When you re done making changes, check that your changes pass flake8 and the tests, as well as provide reasonable test coverage: make release-test Note: This uses the python.exe in your PATH. To change the Python used, run: export PYTHON=/path/to/python # e.g. path to Python 3.4+ 6. Commit your changes and push your branch to GitHub. Then send a pull request: $ git add. $ git commit -m "Your detailed description of your changes." $ git push --set-upstream origin <branch-name> 7. To delete your branch: 18 Chapter 8. More information

git branch -d <branch-name> git push origin --delete <branch-name> 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 and 3.4. Release 1. Test the release by running: make release-test 2. Update version = x.x.x in xmljson 3. Update HISTORY.rst with changes 3. Commit, create an annotated tag and push the code: git commit. git tag -a vx.x.x git push --follow-tags 4. To release to PyPi, run: make clean python setup.py sdist bdist_wheel --universal twine upload dist/* Credits Development Lead S Anand <root.node@gmail.com> Contributors Dag Wieers <dag@wieers.com> 8.2. Credits 19

History 0.1.9 (1 Aug 2017) Bugfix and test cases for multiple nested children in Abdera convention Thanks to @mukultaneja 0.1.8 (9 May 2017) Add Abdera and Cobra conventions Add Parker.data(preserve_root=True) option to preserve root element in Parker convention. Thanks to @dagwieers 0.1.6 (18 Feb 2016) Add xml_fromstring= and xml_tostring= parameters to constructor to customise string conversion from and to XML. 0.1.5 (23 Sep 2015) Add the Yahoo XML to JSON conversion method. 0.1.4 (20 Sep 2015) Fix GData.etree() conversion of attributes. (They were ignored. They should be added as-is.) 0.1.3 (20 Sep 2015) Simplify {'p': {'$': 'text'}} to {'p': 'text'} in BadgerFish and GData conventions. Add test cases for.etree() mainly from the MDN JXON article. dict_type/list_type do not need to inherit from dict/list 0.1.2 (18 Sep 2015) Always use the dict_type class to create dictionaries (which defaults to OrderedDict to preserve order of keys) Update documentation, test cases Remove support for Python 2.6 (since we need collections.counter) Make the Travis CI build pass 20 Chapter 8. More information

0.1.1 (18 Sep 2015) Convert true, false and numeric values from strings to Python types xmljson.parker.data() is compliant with Parker convention (bugs resolved) 0.1.0 (15 Sep 2015) Two-way conversions via BadgerFish, GData and Parker conventions. First release on PyPI. Indices and tables genindex modindex search 8.4. Indices and tables 21