jsonutil.py
229 lines
| 7.3 KiB
| text/x-python
|
PythonLexer
Fernando Perez
|
r2947 | """Utilities to manipulate JSON objects. | ||
""" | ||||
#----------------------------------------------------------------------------- | ||||
Matthias BUSSONNIER
|
r5390 | # Copyright (C) 2010-2011 The IPython Development Team | ||
Fernando Perez
|
r2947 | # | ||
# Distributed under the terms of the BSD License. The full license is in | ||||
# the file COPYING.txt, distributed as part of this software. | ||||
#----------------------------------------------------------------------------- | ||||
#----------------------------------------------------------------------------- | ||||
# Imports | ||||
#----------------------------------------------------------------------------- | ||||
# stdlib | ||||
MinRK
|
r8022 | import math | ||
MinRK
|
r4006 | import re | ||
Fernando Perez
|
r2947 | import types | ||
MinRK
|
r4006 | from datetime import datetime | ||
Mikhail Korobov
|
r9041 | try: | ||
# base64.encodestring is deprecated in Python 3.x | ||||
from base64 import encodebytes | ||||
except ImportError: | ||||
# Python 2.x | ||||
from base64 import encodestring as encodebytes | ||||
Thomas Kluyver
|
r4764 | from IPython.utils import py3compat | ||
Thomas Kluyver
|
r13361 | from IPython.utils.py3compat import string_types, unicode_type, iteritems | ||
Brandon Parsons
|
r6716 | from IPython.utils.encoding import DEFAULT_ENCODING | ||
Thomas Kluyver
|
r4764 | next_attr_name = '__next__' if py3compat.PY3 else 'next' | ||
MinRK
|
r4006 | #----------------------------------------------------------------------------- | ||
# Globals and constants | ||||
#----------------------------------------------------------------------------- | ||||
# timestamp formats | ||||
ISO8601="%Y-%m-%dT%H:%M:%S.%f" | ||||
MinRK
|
r11150 | ISO8601_PAT=re.compile(r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+)Z?([\+\-]\d{2}:?\d{2})?$") | ||
Fernando Perez
|
r2947 | |||
#----------------------------------------------------------------------------- | ||||
# Classes and functions | ||||
#----------------------------------------------------------------------------- | ||||
MinRK
|
r4036 | def rekey(dikt): | ||
"""Rekey a dict that has been forced to use str keys where there should be | ||||
ints by json.""" | ||||
Thomas Kluyver
|
r13360 | for k in dikt: | ||
Thomas Kluyver
|
r13353 | if isinstance(k, string_types): | ||
MinRK
|
r4036 | ik=fk=None | ||
try: | ||||
ik = int(k) | ||||
except ValueError: | ||||
try: | ||||
fk = float(k) | ||||
except ValueError: | ||||
continue | ||||
if ik is not None: | ||||
nk = ik | ||||
else: | ||||
nk = fk | ||||
if nk in dikt: | ||||
raise KeyError("already have key %r"%nk) | ||||
dikt[nk] = dikt.pop(k) | ||||
return dikt | ||||
MinRK
|
r4006 | def extract_dates(obj): | ||
"""extract ISO8601 dates from unpacked JSON""" | ||||
if isinstance(obj, dict): | ||||
MinRK
|
r4010 | obj = dict(obj) # don't clobber | ||
Thomas Kluyver
|
r13361 | for k,v in iteritems(obj): | ||
MinRK
|
r4006 | obj[k] = extract_dates(v) | ||
MinRK
|
r4008 | elif isinstance(obj, (list, tuple)): | ||
MinRK
|
r4006 | obj = [ extract_dates(o) for o in obj ] | ||
Thomas Kluyver
|
r13353 | elif isinstance(obj, string_types): | ||
MinRK
|
r11150 | m = ISO8601_PAT.match(obj) | ||
if m: | ||||
MinRK
|
r11143 | # FIXME: add actual timezone support | ||
MinRK
|
r11150 | # this just drops the timezone info | ||
notz = m.groups()[0] | ||||
MinRK
|
r11143 | obj = datetime.strptime(notz, ISO8601) | ||
MinRK
|
r4006 | return obj | ||
MinRK
|
r4008 | def squash_dates(obj): | ||
"""squash datetime objects into ISO8601 strings""" | ||||
if isinstance(obj, dict): | ||||
MinRK
|
r4010 | obj = dict(obj) # don't clobber | ||
Thomas Kluyver
|
r13361 | for k,v in iteritems(obj): | ||
MinRK
|
r4008 | obj[k] = squash_dates(v) | ||
elif isinstance(obj, (list, tuple)): | ||||
obj = [ squash_dates(o) for o in obj ] | ||||
elif isinstance(obj, datetime): | ||||
MinRK
|
r11143 | obj = obj.isoformat() | ||
MinRK
|
r4008 | return obj | ||
Mikhail Korobov
|
r9041 | |||
MinRK
|
r4006 | def date_default(obj): | ||
MinRK
|
r4008 | """default function for packing datetime objects in JSON.""" | ||
MinRK
|
r4006 | if isinstance(obj, datetime): | ||
MinRK
|
r11143 | return obj.isoformat() | ||
MinRK
|
r4006 | else: | ||
raise TypeError("%r is not JSON serializable"%obj) | ||||
MinRK
|
r7737 | # constants for identifying png/jpeg data | ||
PNG = b'\x89PNG\r\n\x1a\n' | ||||
MinRK
|
r10051 | # front of PNG base64-encoded | ||
PNG64 = b'iVBORw0KG' | ||||
MinRK
|
r7737 | JPEG = b'\xff\xd8' | ||
MinRK
|
r10051 | # front of JPEG base64-encoded | ||
JPEG64 = b'/9' | ||||
MinRK
|
r7737 | |||
def encode_images(format_dict): | ||||
"""b64-encodes images in a displaypub format dict | ||||
Mikhail Korobov
|
r9041 | |||
MinRK
|
r7737 | Perhaps this should be handled in json_clean itself? | ||
Mikhail Korobov
|
r9041 | |||
MinRK
|
r7746 | Parameters | ||
---------- | ||||
Mikhail Korobov
|
r9041 | |||
MinRK
|
r7746 | format_dict : dict | ||
A dictionary of display data keyed by mime-type | ||||
Mikhail Korobov
|
r9041 | |||
MinRK
|
r7746 | Returns | ||
------- | ||||
Mikhail Korobov
|
r9041 | |||
MinRK
|
r7746 | format_dict : dict | ||
A copy of the same dictionary, | ||||
but binary image data ('image/png' or 'image/jpeg') | ||||
is base64-encoded. | ||||
Mikhail Korobov
|
r9041 | |||
MinRK
|
r7737 | """ | ||
encoded = format_dict.copy() | ||||
MinRK
|
r10048 | |||
MinRK
|
r7737 | pngdata = format_dict.get('image/png') | ||
MinRK
|
r10048 | if isinstance(pngdata, bytes): | ||
# make sure we don't double-encode | ||||
MinRK
|
r10051 | if not pngdata.startswith(PNG64): | ||
MinRK
|
r10048 | pngdata = encodebytes(pngdata) | ||
encoded['image/png'] = pngdata.decode('ascii') | ||||
MinRK
|
r7737 | jpegdata = format_dict.get('image/jpeg') | ||
MinRK
|
r10048 | if isinstance(jpegdata, bytes): | ||
# make sure we don't double-encode | ||||
MinRK
|
r10051 | if not jpegdata.startswith(JPEG64): | ||
MinRK
|
r10048 | jpegdata = encodebytes(jpegdata) | ||
encoded['image/jpeg'] = jpegdata.decode('ascii') | ||||
MinRK
|
r7737 | return encoded | ||
MinRK
|
r4006 | |||
Fernando Perez
|
r2947 | def json_clean(obj): | ||
"""Clean an object to ensure it's safe to encode in JSON. | ||||
Mikhail Korobov
|
r9041 | |||
Fernando Perez
|
r2947 | Atomic, immutable objects are returned unmodified. Sets and tuples are | ||
converted to lists, lists are copied and dicts are also copied. | ||||
Note: dicts whose keys could cause collisions upon encoding (such as a dict | ||||
with both the number 1 and the string '1' as keys) will cause a ValueError | ||||
to be raised. | ||||
Parameters | ||||
---------- | ||||
obj : any python object | ||||
Returns | ||||
------- | ||||
out : object | ||||
Mikhail Korobov
|
r9041 | |||
Fernando Perez
|
r2947 | A version of the input which will not cause an encoding error when | ||
encoded as JSON. Note that this function does not *encode* its inputs, | ||||
it simply sanitizes it so that there will be no encoding errors later. | ||||
Examples | ||||
-------- | ||||
>>> json_clean(4) | ||||
4 | ||||
Thomas Kluyver
|
r13373 | >>> json_clean(list(range(10))) | ||
Fernando Perez
|
r2947 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | ||
Thomas Kluyver
|
r7012 | >>> sorted(json_clean(dict(x=1, y=2)).items()) | ||
[('x', 1), ('y', 2)] | ||||
>>> sorted(json_clean(dict(x=1, y=2, z=[1,2,3])).items()) | ||||
[('x', 1), ('y', 2), ('z', [1, 2, 3])] | ||||
Fernando Perez
|
r2947 | >>> json_clean(True) | ||
True | ||||
""" | ||||
# types that are 'atomic' and ok in json as-is. bool doesn't need to be | ||||
# listed explicitly because bools pass as int instances | ||||
Thomas Kluyver
|
r13372 | atomic_ok = (unicode_type, int, type(None)) | ||
Mikhail Korobov
|
r9041 | |||
Fernando Perez
|
r2947 | # containers that we need to convert into lists | ||
container_to_list = (tuple, set, types.GeneratorType) | ||||
Mikhail Korobov
|
r9041 | |||
MinRK
|
r8021 | if isinstance(obj, float): | ||
# cast out-of-range floats to their reprs | ||||
MinRK
|
r8022 | if math.isnan(obj) or math.isinf(obj): | ||
MinRK
|
r8021 | return repr(obj) | ||
return obj | ||||
Mikhail Korobov
|
r9041 | |||
Fernando Perez
|
r2947 | if isinstance(obj, atomic_ok): | ||
return obj | ||||
Mikhail Korobov
|
r9041 | |||
MinRK
|
r4719 | if isinstance(obj, bytes): | ||
Brandon Parsons
|
r6716 | return obj.decode(DEFAULT_ENCODING, 'replace') | ||
Mikhail Korobov
|
r9041 | |||
Fernando Perez
|
r2947 | if isinstance(obj, container_to_list) or ( | ||
Thomas Kluyver
|
r4764 | hasattr(obj, '__iter__') and hasattr(obj, next_attr_name)): | ||
Fernando Perez
|
r2947 | obj = list(obj) | ||
Mikhail Korobov
|
r9041 | |||
Fernando Perez
|
r2947 | if isinstance(obj, list): | ||
return [json_clean(x) for x in obj] | ||||
if isinstance(obj, dict): | ||||
# First, validate that the dict won't lose data in conversion due to | ||||
# key collisions after stringification. This can happen with keys like | ||||
# True and 'true' or 1 and '1', which collide in JSON. | ||||
nkeys = len(obj) | ||||
nkeys_collapsed = len(set(map(str, obj))) | ||||
if nkeys != nkeys_collapsed: | ||||
raise ValueError('dict can not be safely converted to JSON: ' | ||||
'key collision would lead to dropped values') | ||||
# If all OK, proceed by making the new dict that will be json-safe | ||||
out = {} | ||||
Thomas Kluyver
|
r13361 | for k,v in iteritems(obj): | ||
Fernando Perez
|
r2947 | out[str(k)] = json_clean(v) | ||
return out | ||||
# If we get here, we don't know how to handle the object, so we just get | ||||
# its repr and return that. This will catch lambdas, open sockets, class | ||||
# objects, and any other complicated contraption that json can't encode | ||||
return repr(obj) | ||||