Project

General

Profile

JysonEncoding » History » Version 2

Alan Kennedy, 2009-03-17 05:04 PM

1 1 Alan Kennedy
h1. Using Jyson for encoding JSON objects.
2 2 Alan Kennedy
3
{{toc}}
4
5
h2. API compatibility with the cpython json module.
6
7
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":http://docs.python.org/library/json.html .
8
9
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)
10
11
<pre>
12
>>> from com.xhaus.jyson import JysonCodec as json
13
>>> json.dumps(["Hello World!"])
14
u'["Hello World!"]'
15
>>>
16
</pre>
17
18
h2. Usage
19
20
To encode a jython object into JSON, simply pass the object to the *dumps()* method, like so
21
22
<pre>
23
>>> from com.xhaus.jyson import JysonCodec as json
24
>>> my_object = {"hello": "world", "integer": 42, "float": 42.0}
25
>>> json.dumps(my_object)
26
u'{"float":42.0,"integer":42,"hello":"world"}'
27
>>>
28
</pre>
29
30
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).
31
32
h3. Encoding matters
33
34
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
35
36
<pre>
37
>>> from com.xhaus.jyson import JysonCodec as json
38
>>> jython_object = [u"Hello W\u00f6rld"]
39
>>> json_data = json.dumps(jython_object)
40
>>> desired_character_encoding = 'utf-8'
41
>>> encoded_json_data = json_data.encode(desired_character_encoding)
42
>>> json_data
43
u'["Hello W\xf6rld"]'
44
>>> encoded_json_data
45
'["Hello W\xc3\xb6rld"]'
46
>>>
47
</pre>
48
49
h3. Emitting ASCII
50
51
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 (&#xe1;)).
52
53
<pre>
54
>>> from com.xhaus.jyson import JysonCodec as json
55
>>> s = u"Al\u00e1in"
56
>>> json.dumps(s)
57
u'"Al\xe1in"'
58
>>> json.dumps(s, emit_ascii=True)
59
u'"Al\\u00E1in"'
60
>>>
61
</pre>
62
63
h2. Jython object types supported
64
65
Jyson includes builtin support for encoding the following jython types
66
67
|Type|Implementation type|Example|Notes|
68
|None|org.python.core.Py.None|None||
69
|True, False|org.python.core.Py.True, org.python.core.Py.False|True||
70
|int|org.python.core.PyInteger|42||
71
|long|org.python.core.PyLong|42L||
72
|float|org.python.core.PyFloat|42.0||
73
|str|org.python.core.PyString|"Hello World!"||
74
|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.|
75
|list|org.python.core.PyList|[1, 42, "Hello world!"]|List elements may be of any JSON encodable type, including tuples, lists and dictionaries|
76
|tuple|org.python.core.PyTuple|(1, 42, "Hello world!")|Tuple elements may be of any JSON encodable type, including tuples, lists and dictionaries|
77
78
h2. Encoding your own objects
79
80
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 <pre>__json__()</pre> 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.
81
82
<pre>
83
from com.xhaus.jyson import JysonCodec as json
84
85
class MyTestClass:
86
87
	def __init__(self):
88
		self.i = -1
89
		self.f = -2.0
90
		self.s = 'hi'
91
92
	def __json__(self):
93
		return """{"i":%d, "f":%lf, "s":"%s"}""" % (abs(self.i), abs(self.f), self.s.upper())
94
95
mtc = MyTestClass()
96
print json.dumps(mtc)
97
</pre>
98
99
Which outputs
100
101
<pre>
102
{"i":1, "f":2.000000, "s":"HI"}
103
</pre>