Project

General

Profile

Actions

JysonEncoding » History » Revision 2

« Previous | Revision 2/3 (diff) | Next »
Alan Kennedy, 2009-03-17 05:04 PM


Using Jyson for encoding JSON objects.

API compatibility with the cpython json module.

When I originally wrote jyson, I devised my own api, to make it suitable for usage both from jython and from java. However, as discussed on the wiki front page, I have decided that it is better for jyson to use the same API as the cpython json module .

Therefore, I have changed the jyson API to be closer to the json module API, a process that is not yet complete. However, the API can be made the same at a higher level, by using it like this (assuming that you have placed the jyson.jar file on your classpath)

>>> from com.xhaus.jyson import JysonCodec as json
>>> json.dumps(["Hello World!"])
u'["Hello World!"]'
>>>

Usage

To encode a jython object into JSON, simply pass the object to the dumps() method, like so

>>> from com.xhaus.jyson import JysonCodec as json
>>> my_object = {"hello": "world", "integer": 42, "float": 42.0}
>>> json.dumps(my_object)
u'{"float":42.0,"integer":42,"hello":"world"}'
>>>

You will notice that, because of the syntactic similarities of python/jython and javascript, the JSON representation and jython representation of the object is the same (although the order of dictionary keys may be different).

Encoding matters

The JSON string returned from the dumps() operation is a java.lang.String, i.e. it is not byte encoded. If you want for the string to be byte encoded, then you should do this encoding yourself. The following code sample achieves this

>>> from com.xhaus.jyson import JysonCodec as json
>>> jython_object = [u"Hello W\u00f6rld"]
>>> json_data = json.dumps(jython_object)
>>> desired_character_encoding = 'utf-8'
>>> encoded_json_data = json_data.encode(desired_character_encoding)
>>> json_data
u'["Hello W\xf6rld"]'
>>> encoded_json_data
'["Hello W\xc3\xb6rld"]'
>>>

Emitting ASCII

Jyson has a single option whch controls the output character set of the encoding operation: emit_ascii. If this option is true, then all characters with a Unicode value above 127 will be encoded as Unicode escapes. If the option is false, then a standard java Unicode string will be returned. The default value for the emit_ascii option is False. The following illustrates the principle (assuming you run it on a terminal which will display Unicode character \u00e1 as an accented a (á)).

>>> from com.xhaus.jyson import JysonCodec as json
>>> s = u"Al\u00e1in" 
>>> json.dumps(s)
u'"Al\xe1in"'
>>> json.dumps(s, emit_ascii=True)
u'"Al\\u00E1in"'
>>>

Jython object types supported

Jyson includes builtin support for encoding the following jython types

Type Implementation type Example Notes
None org.python.core.Py.None None
True, False org.python.core.Py.True, org.python.core.Py.False True
int org.python.core.PyInteger 42
long org.python.core.PyLong 42L
float org.python.core.PyFloat 42.0
str org.python.core.PyString "Hello World!"
dict org.python.core.PyDictionary, org.python.core.PyStringMap {"hello": 1, "world": 2} Only dictionaries with string keys can be encoded, as according to the JSON spec. Any attempt to encode a dictionary with a non-string key will cause a JysonEncodeException. The values in a dictionary can be any JSON encodable type, including tuples, lists and dictionaries.
list org.python.core.PyList [1, 42, "Hello world!"] List elements may be of any JSON encodable type, including tuples, lists and dictionaries
tuple org.python.core.PyTuple (1, 42, "Hello world!") Tuple elements may be of any JSON encodable type, including tuples, lists and dictionaries

Encoding your own objects

If you wish to encode objects that include elements not contained in the above table, but are still representable in JSON, then you can control the JSON generation process by implementing a

__json__()
method on your objects. If you do so, then this method will be invoked at JSON generation time, and should return the JSON corresponding to your object. The return JSON text is not checked for correctness: that is your responsiblity. Here is some sample code.

from com.xhaus.jyson import JysonCodec as json

class MyTestClass:

    def __init__(self):
        self.i = -1
        self.f = -2.0
        self.s = 'hi'

    def __json__(self):
        return """{"i":%d, "f":%lf, "s":"%s"}""" % (abs(self.i), abs(self.f), self.s.upper())

mtc = MyTestClass()
print json.dumps(mtc)

Which outputs

{"i":1, "f":2.000000, "s":"HI"}

Updated by Alan Kennedy about 15 years ago · 2 revisions