Project

General

Profile

Actions

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"]'
>>>

Options to control the encoding process

The options you can specify to control the JSON generation process with jyson are desribed on the jyson encode options page.

How jyson maps jython objects to JSON objects

Jyson maps specific jython object type to JSON object types in a specific way: this mapping is described on the jyson encode mappings page.

Generating JSON representations of user classes and objects.

Jyson can generate JSON representations of user classes and objects: how to do this is described on the representing user objects in JSON page.

Updated by Alan Kennedy about 15 years ago ยท 3 revisions