
git-svn-id: svn://svn.cy55.de/Zope3/src/cybertools/trunk@2986 fd906abe-77d9-0310-91a1-e0d9ade77398
64 lines
2 KiB
Text
64 lines
2 KiB
Text
==========================
|
|
JSON Endoding and Decoding
|
|
==========================
|
|
|
|
$Id$
|
|
|
|
This is a stripped-down version of simplejson
|
|
by Bob Ippolito, http://undefined.org/python/
|
|
|
|
Copyright (c) 2006 Bob Ippolito
|
|
|
|
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
this software and associated documentation files (the "Software"), to deal in
|
|
the Software without restriction, including without limitation the rights to
|
|
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
|
of the Software, and to permit persons to whom the Software is furnished to do
|
|
so, subject to the following conditions:
|
|
|
|
The above copyright notice and this permission notice shall be included in all
|
|
copies or substantial portions of the Software.
|
|
|
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
SOFTWARE.
|
|
|
|
>>> from cybertools.util.json import dumps, loads
|
|
|
|
Encoding basic Python object hierarchies::
|
|
|
|
>>> dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
|
|
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
|
|
>>> print dumps("\"foo\bar")
|
|
"\"foo\bar"
|
|
>>> print dumps(u'\u1234')
|
|
"\u1234"
|
|
>>> print dumps('\\')
|
|
"\\"
|
|
>>> print dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
|
|
{"a": 0, "b": 0, "c": 0}
|
|
|
|
Compact encoding::
|
|
|
|
>>> dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':'))
|
|
'[1,2,3,{"4":5,"6":7}]'
|
|
|
|
Pretty printing::
|
|
|
|
>>> print dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
|
|
{
|
|
"4": 5,
|
|
"6": 7
|
|
}
|
|
|
|
Decoding JSON::
|
|
|
|
>>> loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
|
|
[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
|
|
>>> loads('"\\"foo\\bar"')
|
|
u'"foo\x08ar'
|
|
|