JSON (JavaScript Object Notation) <http://json.org> is a subset of JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data interchange format.
simplejson exposes an API familiar to users of the standard library marshal and pickle modules. It is the externally maintained version of the json library contained in Python 2.6, but maintains compatibility with Python 2.4 and Python 2.5 and (currently) has significant performance advantages, even without using the optional C extension for speedups.
Using simplejson.tool from the shell to validate and pretty-print:
$ echo '{"json":"obj"}' | python -msimplejson.tool
{
"json": "obj"
}
$ echo '{ 1.2:3.4}' | python -msimplejson.tool
Expecting property name: line 1 column 2 (char 2)
Implementation of JSONDecoder
Bases: object
Simple JSON <http://json.org> decoder
Performs the following translations in decoding by default:
JSON | Python |
---|---|
object | dict |
array | list |
string | unicode |
number (int) | int, long |
number (real) | float |
true | True |
false | False |
null | None |
It also understands NaN, Infinity, and -Infinity as their corresponding float values, which is outside the JSON spec.
Return the Python representation of s (a str or unicode instance containing a JSON document)
Decode a JSON document from s (a str or unicode beginning with a JSON document) and return a 2-tuple of the Python representation and the index in s where the document ended.
This can be used to decode a JSON document from a string that may have extraneous data at the end.
Implementation of JSONEncoder
Bases: object
Extensible JSON <http://json.org> encoder for Python data structures.
Supports the following objects and types by default:
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str, unicode | string |
int, long, float | number |
True | true |
False | false |
None | null |
To extend this to recognize other objects, subclass and implement a .default() method with another method that returns a serializable object for o if possible, otherwise it should call the superclass implementation (to raise TypeError).
Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).
For example, to support arbitrary iterators, you could implement default like this:
def default(self, o):
try:
iterable = iter(o)
except TypeError:
pass
else:
return list(iterable)
return JSONEncoder.default(self, o)
Return a JSON string representation of a Python data structure.
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
Encode the given object and yield each string representation as available.
For example:
for chunk in JSONEncoder().iterencode(bigobject):
mysocket.write(chunk)
Return a JSON representation of a Python string
Return an ASCII-only JSON representation of a Python string