This module contains methods and classes to extend json encoding and decoding
to cover timestamps, uuids, and fractions. The mutable types are provided by
default and if you require the immutable types then import from immutable instead.
To make use of it either use the dumps, loads, dump, and load functions in
place of the versions from the standard json module, or use the classes
NMOSJSONEncoder and NMOSJSONDecoder as your encoder and decoder classes.
1# Copyright 2017 British Broadcasting Corporation 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.1415"""16This module contains methods and classes to extend json encoding and decoding17to cover timestamps, uuids, and fractions. The mutable types are provided by18default and if you require the immutable types then import from immutable instead.1920To make use of it either use the dumps, loads, dump, and load functions in21place of the versions from the standard json module, or use the classes22NMOSJSONEncoder and NMOSJSONDecoder as your encoder and decoder classes.23"""2425fromjsonimportJSONEncoder,JSONDecoder2627from.encodeimportdump,dumps,encode_value,NMOSJSONEncoder28from.decodeimportload,loads,decode_value,NMOSJSONDecoder293031__all__=["dump","dumps","load","loads",32"encode_value","decode_value",33"JSONEncoder","JSONDecoder",34"NMOSJSONEncoder","NMOSJSONDecoder"]
75classJSONEncoder(object): 76"""Extensible JSON <https://json.org> encoder for Python data structures. 77 78 Supports the following objects and types by default: 79 80 +-------------------+---------------+ 81 | Python | JSON | 82 +===================+===============+ 83 | dict | object | 84 +-------------------+---------------+ 85 | list, tuple | array | 86 +-------------------+---------------+ 87 | str | string | 88 +-------------------+---------------+ 89 | int, float | number | 90 +-------------------+---------------+ 91 | True | true | 92 +-------------------+---------------+ 93 | False | false | 94 +-------------------+---------------+ 95 | None | null | 96 +-------------------+---------------+ 97 98 To extend this to recognize other objects, subclass and implement a 99 ``.default()`` method with another method that returns a serializable100 object for ``o`` if possible, otherwise it should call the superclass101 implementation (to raise ``TypeError``).102103 """104item_separator=', '105key_separator=': '106def__init__(self,*,skipkeys=False,ensure_ascii=True,107check_circular=True,allow_nan=True,sort_keys=False,108indent=None,separators=None,default=None):109"""Constructor for JSONEncoder, with sensible defaults.110111 If skipkeys is false, then it is a TypeError to attempt112 encoding of keys that are not str, int, float or None. If113 skipkeys is True, such items are simply skipped.114115 If ensure_ascii is true, the output is guaranteed to be str116 objects with all incoming non-ASCII characters escaped. If117 ensure_ascii is false, the output can contain non-ASCII characters.118119 If check_circular is true, then lists, dicts, and custom encoded120 objects will be checked for circular references during encoding to121 prevent an infinite recursion (which would cause an RecursionError).122 Otherwise, no such check takes place.123124 If allow_nan is true, then NaN, Infinity, and -Infinity will be125 encoded as such. This behavior is not JSON specification compliant,126 but is consistent with most JavaScript based encoders and decoders.127 Otherwise, it will be a ValueError to encode such floats.128129 If sort_keys is true, then the output of dictionaries will be130 sorted by key; this is useful for regression tests to ensure131 that JSON serializations can be compared on a day-to-day basis.132133 If indent is a non-negative integer, then JSON array134 elements and object members will be pretty-printed with that135 indent level. An indent level of 0 will only insert newlines.136 None is the most compact representation.137138 If specified, separators should be an (item_separator, key_separator)139 tuple. The default is (', ', ': ') if *indent* is ``None`` and140 (',', ': ') otherwise. To get the most compact JSON representation,141 you should specify (',', ':') to eliminate whitespace.142143 If specified, default is a function that gets called for objects144 that can't otherwise be serialized. It should return a JSON encodable145 version of the object or raise a ``TypeError``.146147 """148149self.skipkeys=skipkeys150self.ensure_ascii=ensure_ascii151self.check_circular=check_circular152self.allow_nan=allow_nan153self.sort_keys=sort_keys154self.indent=indent155ifseparatorsisnotNone:156self.item_separator,self.key_separator=separators157elifindentisnotNone:158self.item_separator=','159ifdefaultisnotNone:160self.default=default161162defdefault(self,o):163"""Implement this method in a subclass such that it returns164 a serializable object for ``o``, or calls the base implementation165 (to raise a ``TypeError``).166167 For example, to support arbitrary iterators, you could168 implement default like this::169170 def default(self, o):171 try:172 iterable = iter(o)173 except TypeError:174 pass175 else:176 return list(iterable)177 # Let the base class default method raise the TypeError178 return super().default(o)179180 """181raiseTypeError(f'Object of type {o.__class__.__name__} '182f'is not JSON serializable')183184defencode(self,o):185"""Return a JSON string representation of a Python data structure.186187 >>> from json.encoder import JSONEncoder188 >>> JSONEncoder().encode({"foo": ["bar", "baz"]})189 '{"foo": ["bar", "baz"]}'190191 """192# This is for extremely simple cases and benchmarks.193ifisinstance(o,str):194ifself.ensure_ascii:195returnencode_basestring_ascii(o)196else:197returnencode_basestring(o)198# This doesn't pass the iterator directly to ''.join() because the199# exceptions aren't as detailed. The list call should be roughly200# equivalent to the PySequence_Fast that ''.join() would do.201chunks=self.iterencode(o,_one_shot=True)202ifnotisinstance(chunks,(list,tuple)):203chunks=list(chunks)204return''.join(chunks)205206defiterencode(self,o,_one_shot=False):207"""Encode the given object and yield each string208 representation as available.209210 For example::211212 for chunk in JSONEncoder().iterencode(bigobject):213 mysocket.write(chunk)214215 """216ifself.check_circular:217markers={}218else:219markers=None220ifself.ensure_ascii:221_encoder=encode_basestring_ascii222else:223_encoder=encode_basestring224225deffloatstr(o,allow_nan=self.allow_nan,226_repr=float.__repr__,_inf=INFINITY,_neginf=-INFINITY):227# Check for specials. Note that this type of test is processor228# and/or platform-specific, so do tests which don't depend on the229# internals.230231ifo!=o:232text='NaN'233elifo==_inf:234text='Infinity'235elifo==_neginf:236text='-Infinity'237else:238return_repr(o)239240ifnotallow_nan:241raiseValueError(242"Out of range float values are not JSON compliant: "+243repr(o))244245returntext246247248if(_one_shotandc_make_encoderisnotNone249andself.indentisNone):250_iterencode=c_make_encoder(251markers,self.default,_encoder,self.indent,252self.key_separator,self.item_separator,self.sort_keys,253self.skipkeys,self.allow_nan)254else:255_iterencode=_make_iterencode(256markers,self.default,_encoder,self.indent,floatstr,257self.key_separator,self.item_separator,self.sort_keys,258self.skipkeys,_one_shot)259return_iterencode(o,0)
Extensible JSON https://json.org encoder for Python data structures.
Supports the following objects and types by default:
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).
106def__init__(self,*,skipkeys=False,ensure_ascii=True,107check_circular=True,allow_nan=True,sort_keys=False,108indent=None,separators=None,default=None):109"""Constructor for JSONEncoder, with sensible defaults.110111 If skipkeys is false, then it is a TypeError to attempt112 encoding of keys that are not str, int, float or None. If113 skipkeys is True, such items are simply skipped.114115 If ensure_ascii is true, the output is guaranteed to be str116 objects with all incoming non-ASCII characters escaped. If117 ensure_ascii is false, the output can contain non-ASCII characters.118119 If check_circular is true, then lists, dicts, and custom encoded120 objects will be checked for circular references during encoding to121 prevent an infinite recursion (which would cause an RecursionError).122 Otherwise, no such check takes place.123124 If allow_nan is true, then NaN, Infinity, and -Infinity will be125 encoded as such. This behavior is not JSON specification compliant,126 but is consistent with most JavaScript based encoders and decoders.127 Otherwise, it will be a ValueError to encode such floats.128129 If sort_keys is true, then the output of dictionaries will be130 sorted by key; this is useful for regression tests to ensure131 that JSON serializations can be compared on a day-to-day basis.132133 If indent is a non-negative integer, then JSON array134 elements and object members will be pretty-printed with that135 indent level. An indent level of 0 will only insert newlines.136 None is the most compact representation.137138 If specified, separators should be an (item_separator, key_separator)139 tuple. The default is (', ', ': ') if *indent* is ``None`` and140 (',', ': ') otherwise. To get the most compact JSON representation,141 you should specify (',', ':') to eliminate whitespace.142143 If specified, default is a function that gets called for objects144 that can't otherwise be serialized. It should return a JSON encodable145 version of the object or raise a ``TypeError``.146147 """148149self.skipkeys=skipkeys150self.ensure_ascii=ensure_ascii151self.check_circular=check_circular152self.allow_nan=allow_nan153self.sort_keys=sort_keys154self.indent=indent155ifseparatorsisnotNone:156self.item_separator,self.key_separator=separators157elifindentisnotNone:158self.item_separator=','159ifdefaultisnotNone:160self.default=default
Constructor for JSONEncoder, with sensible defaults.
If skipkeys is false, then it is a TypeError to attempt
encoding of keys that are not str, int, float or None. If
skipkeys is True, such items are simply skipped.
If ensure_ascii is true, the output is guaranteed to be str
objects with all incoming non-ASCII characters escaped. If
ensure_ascii is false, the output can contain non-ASCII characters.
If check_circular is true, then lists, dicts, and custom encoded
objects will be checked for circular references during encoding to
prevent an infinite recursion (which would cause an RecursionError).
Otherwise, no such check takes place.
If allow_nan is true, then NaN, Infinity, and -Infinity will be
encoded as such. This behavior is not JSON specification compliant,
but is consistent with most JavaScript based encoders and decoders.
Otherwise, it will be a ValueError to encode such floats.
If sort_keys is true, then the output of dictionaries will be
sorted by key; this is useful for regression tests to ensure
that JSON serializations can be compared on a day-to-day basis.
If indent is a non-negative integer, then JSON array
elements and object members will be pretty-printed with that
indent level. An indent level of 0 will only insert newlines.
None is the most compact representation.
If specified, separators should be an (item_separator, key_separator)
tuple. The default is (', ', ': ') if indent is None and
(',', ': ') otherwise. To get the most compact JSON representation,
you should specify (',', ':') to eliminate whitespace.
If specified, default is a function that gets called for objects
that can't otherwise be serialized. It should return a JSON encodable
version of the object or raise a TypeError.
item_separator =
', '
key_separator =
': '
skipkeys
ensure_ascii
check_circular
allow_nan
sort_keys
indent
defdefault(self, o):
162defdefault(self,o):163"""Implement this method in a subclass such that it returns164 a serializable object for ``o``, or calls the base implementation165 (to raise a ``TypeError``).166167 For example, to support arbitrary iterators, you could168 implement default like this::169170 def default(self, o):171 try:172 iterable = iter(o)173 except TypeError:174 pass175 else:176 return list(iterable)177 # Let the base class default method raise the TypeError178 return super().default(o)179180 """181raiseTypeError(f'Object of type {o.__class__.__name__} '182f'is not JSON serializable')
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)
# Let the base class default method raise the TypeError
return super().default(o)
defencode(self, o):
184defencode(self,o):185"""Return a JSON string representation of a Python data structure.186187 >>> from json.encoder import JSONEncoder188 >>> JSONEncoder().encode({"foo": ["bar", "baz"]})189 '{"foo": ["bar", "baz"]}'190191 """192# This is for extremely simple cases and benchmarks.193ifisinstance(o,str):194ifself.ensure_ascii:195returnencode_basestring_ascii(o)196else:197returnencode_basestring(o)198# This doesn't pass the iterator directly to ''.join() because the199# exceptions aren't as detailed. The list call should be roughly200# equivalent to the PySequence_Fast that ''.join() would do.201chunks=self.iterencode(o,_one_shot=True)202ifnotisinstance(chunks,(list,tuple)):203chunks=list(chunks)204return''.join(chunks)
Return a JSON string representation of a Python data structure.
206defiterencode(self,o,_one_shot=False):207"""Encode the given object and yield each string208 representation as available.209210 For example::211212 for chunk in JSONEncoder().iterencode(bigobject):213 mysocket.write(chunk)214215 """216ifself.check_circular:217markers={}218else:219markers=None220ifself.ensure_ascii:221_encoder=encode_basestring_ascii222else:223_encoder=encode_basestring224225deffloatstr(o,allow_nan=self.allow_nan,226_repr=float.__repr__,_inf=INFINITY,_neginf=-INFINITY):227# Check for specials. Note that this type of test is processor228# and/or platform-specific, so do tests which don't depend on the229# internals.230231ifo!=o:232text='NaN'233elifo==_inf:234text='Infinity'235elifo==_neginf:236text='-Infinity'237else:238return_repr(o)239240ifnotallow_nan:241raiseValueError(242"Out of range float values are not JSON compliant: "+243repr(o))244245returntext246247248if(_one_shotandc_make_encoderisnotNone249andself.indentisNone):250_iterencode=c_make_encoder(251markers,self.default,_encoder,self.indent,252self.key_separator,self.item_separator,self.sort_keys,253self.skipkeys,self.allow_nan)254else:255_iterencode=_make_iterencode(256markers,self.default,_encoder,self.indent,floatstr,257self.key_separator,self.item_separator,self.sort_keys,258self.skipkeys,_one_shot)259return_iterencode(o,0)
Encode the given object and yield each string
representation as available.
For example::
for chunk in JSONEncoder().iterencode(bigobject):
mysocket.write(chunk)
classJSONDecoder:
255classJSONDecoder(object):256"""Simple JSON <https://json.org> decoder257258 Performs the following translations in decoding by default:259260 +---------------+-------------------+261 | JSON | Python |262 +===============+===================+263 | object | dict |264 +---------------+-------------------+265 | array | list |266 +---------------+-------------------+267 | string | str |268 +---------------+-------------------+269 | number (int) | int |270 +---------------+-------------------+271 | number (real) | float |272 +---------------+-------------------+273 | true | True |274 +---------------+-------------------+275 | false | False |276 +---------------+-------------------+277 | null | None |278 +---------------+-------------------+279280 It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as281 their corresponding ``float`` values, which is outside the JSON spec.282283 """284285def__init__(self,*,object_hook=None,parse_float=None,286parse_int=None,parse_constant=None,strict=True,287object_pairs_hook=None):288"""``object_hook``, if specified, will be called with the result289 of every JSON object decoded and its return value will be used in290 place of the given ``dict``. This can be used to provide custom291 deserializations (e.g. to support JSON-RPC class hinting).292293 ``object_pairs_hook``, if specified will be called with the result of294 every JSON object decoded with an ordered list of pairs. The return295 value of ``object_pairs_hook`` will be used instead of the ``dict``.296 This feature can be used to implement custom decoders.297 If ``object_hook`` is also defined, the ``object_pairs_hook`` takes298 priority.299300 ``parse_float``, if specified, will be called with the string301 of every JSON float to be decoded. By default this is equivalent to302 float(num_str). This can be used to use another datatype or parser303 for JSON floats (e.g. decimal.Decimal).304305 ``parse_int``, if specified, will be called with the string306 of every JSON int to be decoded. By default this is equivalent to307 int(num_str). This can be used to use another datatype or parser308 for JSON integers (e.g. float).309310 ``parse_constant``, if specified, will be called with one of the311 following strings: -Infinity, Infinity, NaN.312 This can be used to raise an exception if invalid JSON numbers313 are encountered.314315 If ``strict`` is false (true is the default), then control316 characters will be allowed inside strings. Control characters in317 this context are those with character codes in the 0-31 range,318 including ``'\\t'`` (tab), ``'\\n'``, ``'\\r'`` and ``'\\0'``.319 """320self.object_hook=object_hook321self.parse_float=parse_floatorfloat322self.parse_int=parse_intorint323self.parse_constant=parse_constantor_CONSTANTS.__getitem__324self.strict=strict325self.object_pairs_hook=object_pairs_hook326self.parse_object=JSONObject327self.parse_array=JSONArray328self.parse_string=scanstring329self.memo={}330self.scan_once=scanner.make_scanner(self)331332333defdecode(self,s,_w=WHITESPACE.match):334"""Return the Python representation of ``s`` (a ``str`` instance335 containing a JSON document).336337 """338obj,end=self.raw_decode(s,idx=_w(s,0).end())339end=_w(s,end).end()340ifend!=len(s):341raiseJSONDecodeError("Extra data",s,end)342returnobj343344defraw_decode(self,s,idx=0):345"""Decode a JSON document from ``s`` (a ``str`` beginning with346 a JSON document) and return a 2-tuple of the Python347 representation and the index in ``s`` where the document ended.348349 This can be used to decode a JSON document from a string that may350 have extraneous data at the end.351352 """353try:354obj,end=self.scan_once(s,idx)355exceptStopIterationaserr:356raiseJSONDecodeError("Expecting value",s,err.value)fromNone357returnobj,end
285def__init__(self,*,object_hook=None,parse_float=None,286parse_int=None,parse_constant=None,strict=True,287object_pairs_hook=None):288"""``object_hook``, if specified, will be called with the result289 of every JSON object decoded and its return value will be used in290 place of the given ``dict``. This can be used to provide custom291 deserializations (e.g. to support JSON-RPC class hinting).292293 ``object_pairs_hook``, if specified will be called with the result of294 every JSON object decoded with an ordered list of pairs. The return295 value of ``object_pairs_hook`` will be used instead of the ``dict``.296 This feature can be used to implement custom decoders.297 If ``object_hook`` is also defined, the ``object_pairs_hook`` takes298 priority.299300 ``parse_float``, if specified, will be called with the string301 of every JSON float to be decoded. By default this is equivalent to302 float(num_str). This can be used to use another datatype or parser303 for JSON floats (e.g. decimal.Decimal).304305 ``parse_int``, if specified, will be called with the string306 of every JSON int to be decoded. By default this is equivalent to307 int(num_str). This can be used to use another datatype or parser308 for JSON integers (e.g. float).309310 ``parse_constant``, if specified, will be called with one of the311 following strings: -Infinity, Infinity, NaN.312 This can be used to raise an exception if invalid JSON numbers313 are encountered.314315 If ``strict`` is false (true is the default), then control316 characters will be allowed inside strings. Control characters in317 this context are those with character codes in the 0-31 range,318 including ``'\\t'`` (tab), ``'\\n'``, ``'\\r'`` and ``'\\0'``.319 """320self.object_hook=object_hook321self.parse_float=parse_floatorfloat322self.parse_int=parse_intorint323self.parse_constant=parse_constantor_CONSTANTS.__getitem__324self.strict=strict325self.object_pairs_hook=object_pairs_hook326self.parse_object=JSONObject327self.parse_array=JSONArray328self.parse_string=scanstring329self.memo={}330self.scan_once=scanner.make_scanner(self)
object_hook, if specified, will be called with the result
of every JSON object decoded and its return value will be used in
place of the given dict. This can be used to provide custom
deserializations (e.g. to support JSON-RPC class hinting).
object_pairs_hook, if specified will be called with the result of
every JSON object decoded with an ordered list of pairs. The return
value of object_pairs_hook will be used instead of the dict.
This feature can be used to implement custom decoders.
If object_hook is also defined, the object_pairs_hook takes
priority.
parse_float, if specified, will be called with the string
of every JSON float to be decoded. By default this is equivalent to
float(num_str). This can be used to use another datatype or parser
for JSON floats (e.g. decimal.Decimal).
parse_int, if specified, will be called with the string
of every JSON int to be decoded. By default this is equivalent to
int(num_str). This can be used to use another datatype or parser
for JSON integers (e.g. float).
parse_constant, if specified, will be called with one of the
following strings: -Infinity, Infinity, NaN.
This can be used to raise an exception if invalid JSON numbers
are encountered.
If strict is false (true is the default), then control
characters will be allowed inside strings. Control characters in
this context are those with character codes in the 0-31 range,
including '\t' (tab), '\n', '\r' and '\0'.
333defdecode(self,s,_w=WHITESPACE.match):334"""Return the Python representation of ``s`` (a ``str`` instance335 containing a JSON document).336337 """338obj,end=self.raw_decode(s,idx=_w(s,0).end())339end=_w(s,end).end()340ifend!=len(s):341raiseJSONDecodeError("Extra data",s,end)342returnobj
Return the Python representation of s (a str instance
containing a JSON document).
defraw_decode(self, s, idx=0):
344defraw_decode(self,s,idx=0):345"""Decode a JSON document from ``s`` (a ``str`` beginning with346 a JSON document) and return a 2-tuple of the Python347 representation and the index in ``s`` where the document ended.348349 This can be used to decode a JSON document from a string that may350 have extraneous data at the end.351352 """353try:354obj,end=self.scan_once(s,idx)355exceptStopIterationaserr:356raiseJSONDecodeError("Expecting value",s,err.value)fromNone357returnobj,end
Decode a JSON document from s (a str 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.
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)
# Let the base class default method raise the TypeError
return super().default(o)
90classNMOSJSONDecoder(JSONDecoder): 91def__init__(self,**kwargs): 92# Filter out the 'encoding' parameter as a simple workaround for simplejson adding it. 93# The parameter is no longer supported in python 3. 94py3_kwargs={ 95key:value 96for(key,value)inkwargs.items() 97ifkey!="encoding" 98} 99super().__init__(**py3_kwargs)100101defraw_decode(self,s:str,*args,**kwargs)->Tuple[MediaJSONSerialisable,int]:102value:JSONSerialisable103(value,offset)=super(NMOSJSONDecoder,self).raw_decode(s,104*args,105**kwargs)106return(decode_value(value),offset)
It also understands NaN, Infinity, and -Infinity as
their corresponding float values, which is outside the JSON spec.
NMOSJSONDecoder(**kwargs)
91def__init__(self,**kwargs):92# Filter out the 'encoding' parameter as a simple workaround for simplejson adding it.93# The parameter is no longer supported in python 3.94py3_kwargs={95key:value96for(key,value)inkwargs.items()97ifkey!="encoding"98}99super().__init__(**py3_kwargs)
object_hook, if specified, will be called with the result
of every JSON object decoded and its return value will be used in
place of the given dict. This can be used to provide custom
deserializations (e.g. to support JSON-RPC class hinting).
object_pairs_hook, if specified will be called with the result of
every JSON object decoded with an ordered list of pairs. The return
value of object_pairs_hook will be used instead of the dict.
This feature can be used to implement custom decoders.
If object_hook is also defined, the object_pairs_hook takes
priority.
parse_float, if specified, will be called with the string
of every JSON float to be decoded. By default this is equivalent to
float(num_str). This can be used to use another datatype or parser
for JSON floats (e.g. decimal.Decimal).
parse_int, if specified, will be called with the string
of every JSON int to be decoded. By default this is equivalent to
int(num_str). This can be used to use another datatype or parser
for JSON integers (e.g. float).
parse_constant, if specified, will be called with one of the
following strings: -Infinity, Infinity, NaN.
This can be used to raise an exception if invalid JSON numbers
are encountered.
If strict is false (true is the default), then control
characters will be allowed inside strings. Control characters in
this context are those with character codes in the 0-31 range,
including '\t' (tab), '\n', '\r' and '\0'.
Decode a JSON document from s (a str 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.