Project

General

Profile

JysonDecoding » History » Version 3

Alan Kennedy, 2009-03-17 09:01 PM

1 2 Alan Kennedy
h1. Using Jyson to decode json documents
2 1 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 3 Alan Kennedy
Therefore, I have changed the jyson API to be closer to the cpython json module API, a process that is [[JysonCompliance|not yet complete]] . However, you can use a limited subset of the cpython API, by importing jyson like this (assuming that you have placed the jyson.jar file on your classpath)
10 1 Alan Kennedy
11
<pre>
12
>>> from com.xhaus.jyson import JysonCodec as json
13
>>> json.loads('["Hello World!"]')
14
['Hello World!']
15
</pre>
16
17
h2. Usage
18
19
To decode JSON text into jython objects, simply pass the JSON data to the loads method, like so
20
21
<pre>
22
>>> from com.xhaus.jyson import JysonCodec as json
23
>>> json.loads('{"Hello":"World"}')
24
{'Hello': 'World'}
25
>>> json.loads('[1,1.1,null,"Hello World"]')
26
[1, 1.1, None, 'Hello World']
27
>>>
28
</pre>
29
30
h2. Strings passed to jyson must not be byte-encoded
31
32
Note that the string that is passed to the decode method must be a jython string or java.lang.String that is *not byte encoded*. If you wish to decode a string that is byte encoded, then you should decode it yourself first before passing it to the method. The following code illustrates
33
34
<pre>
35
>>> from com.xhaus.jyson import JysonCodec as json
36
>>> utf8_json_data = '["Al\xc3\xa1in"]'
37
>>> decoded_json_data = utf8_json_data.decode('utf-8')
38
>>> decoded_json_data
39
u'["Al\xe1in"]'
40
>>> json.loads(decoded_json_data)
41
['Al\xe1in']
42
>>>
43
</pre>
44
45 3 Alan Kennedy
You might want to read this discussion of [[JysonCompliance#character_encoding|why jyson does not deal with character encodings]].
46 1 Alan Kennedy
47 2 Alan Kennedy
h2. Mappings to jython data types.
48 1 Alan Kennedy
49 2 Alan Kennedy
JSON documents consist of specific datatypes, which jyson maps to specific jython objects. The types to which they are mapped is described on a separate page: [[JysonDecodeMappings|jyson decode mappings]].
50 1 Alan Kennedy
51 2 Alan Kennedy
h2. Options to control the parsing process.
52 1 Alan Kennedy
53 2 Alan Kennedy
Jyson can operate in either *strict* mode, under which all JSON documents must strictly conform to the JSON specification, or in *permissive* mode, under which a variety of non-conformant (but useful) syntactical constructs are accepted. These options are described on a separate page [[JysonDecodeOptions|jyson decode options]].