Home > python > Serializations: data <-> XML, data <-> JSON, XML <->JSON

Serializations: data <-> XML, data <-> JSON, XML <->JSON

Problems

  1. Python data to XML and back
  2. Python data to JSON and back
  3. XML to JSON and back

Solution

import json
import xmlrpclib
from xml2json import Xml2Json

def data_to_xmlrpc(data):
    # http://www.reddit.com/r/Python/comments/ole01/dictionary_to_xml_in_20_lines/
    """Return value: XML RPC string."""
    return xmlrpclib.dumps((data,)) # arg. is tuple

def xmlrpc_to_data(xml):
    # http://www.reddit.com/r/Python/comments/ole01/dictionary_to_xml_in_20_lines/
    """Return value: python data."""
    return xmlrpclib.loads(xml)[0][0]

def data_to_json(data):
    """Return value: JSON string."""
    data_string = json.dumps(data)
    return data_string

def json_to_data(data_string):
    """Return value: python data."""
    data = json.loads(data_string)
    return data

def xml_to_json(xml):
    """Return value: JSON string."""
    res = Xml2Json(xml).result
    return json.dumps(res)

def json_to_xmlrpc(data_string):
    """Return value: XML RPC string."""
    data = json.loads(data_string)
    return data_to_xmlrpc(data)

def xmlrpc_to_json(xmlrpc):
    """Return value: JSON string."""
    data = xmlrpc_to_data(xmlrpc)
    return data_to_json(data)

The full source code (serialize.py) together with the imported xml2json.py are available here. This work is part of my jabbapylib library.

Examples
Unit tests are here, they show you how to use these functions. Examples with comments are here.

Advertisements
Categories: python Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: