Skip to content

Commit b106b59

Browse files
committed
Starting to work on doc and test
1 parent dd0a310 commit b106b59

File tree

3 files changed

+48
-239
lines changed

3 files changed

+48
-239
lines changed

Doc/library/json.rst

Lines changed: 35 additions & 226 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
:mod:`!json` --- JSON encoder and decoder
1+
:mod:`!json` --- JSON encoder and decoder
22
=========================================
33

44
.. module:: json
@@ -99,22 +99,21 @@ Specializing JSON object decoding::
9999
Decimal('1.1')
100100

101101
Extending :class:`JSONEncoder`::
102-
103-
>>> import json
104-
>>> class ComplexEncoder(json.JSONEncoder):
105-
... def default(self, obj):
106-
... if isinstance(obj, complex):
107-
... return [obj.real, obj.imag]
108-
... # Let the base class default method raise the TypeError
109-
... return super().default(obj)
110-
...
111-
>>> json.dumps(2 + 1j, cls=ComplexEncoder)
112-
'[2.0, 1.0]'
113-
>>> ComplexEncoder().encode(2 + 1j)
114-
'[2.0, 1.0]'
115-
>>> list(ComplexEncoder().iterencode(2 + 1j))
116-
['[2.0', ', 1.0', ']']
117-
102+
103+
>>> import json
104+
>>> class ComplexEncoder(json.JSONEncoder):
105+
... def default(self, obj):
106+
... if isinstance(obj, complex):
107+
... return [obj.real, obj.imag]
108+
... # Let the base class default method raise the TypeError
109+
... return super().default(obj)
110+
...
111+
>>> json.dumps(2 + 1j, cls=ComplexEncoder)
112+
'[2.0, 1.0]'
113+
>>> ComplexEncoder().encode(2 + 1j)
114+
'[2.0, 1.0]'
115+
>>> list(ComplexEncoder().iterencode(2 + 1j))
116+
['[2.0', ', 1.0', ']']
118117

119118
Using :mod:`json` from the shell to validate and pretty-print:
120119

@@ -230,15 +229,15 @@ Basic Usage
230229
If ``True``, dictionaries will be outputted sorted by key.
231230
Default ``False``.
232231

233-
.. versionchanged:: 3.2
234-
Allow strings for *indent* in addition to integers.
235-
236-
.. versionchanged:: 3.4
237-
Use ``(',', ': ')`` as default if *indent* is not ``None``.
238-
239232
.. versionchanged:: 3.6
240233
All optional parameters are now :ref:`keyword-only <keyword-only_parameter>`.
241234

235+
:param bool arr_oneline:
236+
**New in this release.**
237+
If ``True``, JSON arrays (Python lists and tuples) will be serialized
238+
on a single line regardless of the specified *indent* level. This allows
239+
for a more compact representation of array data while still pretty-printing
240+
objects. Default is ``False``.
242241

243242
.. function:: dumps(obj, *, skipkeys=False, ensure_ascii=True, \
244243
check_circular=True, allow_nan=True, cls=None, \
@@ -258,200 +257,12 @@ Basic Usage
258257
the original one. That is, ``loads(dumps(x)) != x`` if x has non-string
259258
keys.
260259

261-
.. function:: load(fp, *, cls=None, object_hook=None, parse_float=None, \
262-
parse_int=None, parse_constant=None, \
263-
object_pairs_hook=None, **kw)
264-
265-
Deserialize *fp* to a Python object
266-
using the :ref:`JSON-to-Python conversion table <json-to-py-table>`.
267-
268-
:param fp:
269-
A ``.read()``-supporting :term:`text file` or :term:`binary file`
270-
containing the JSON document to be deserialized.
271-
:type fp: :term:`file-like object`
272-
273-
:param cls:
274-
If set, a custom JSON decoder.
275-
Additional keyword arguments to :func:`!load`
276-
will be passed to the constructor of *cls*.
277-
If ``None`` (the default), :class:`!JSONDecoder` is used.
278-
:type cls: a :class:`JSONDecoder` subclass
279-
280-
:param object_hook:
281-
If set, a function that is called with the result of
282-
any object literal decoded (a :class:`dict`).
283-
The return value of this function will be used
284-
instead of the :class:`dict`.
285-
This feature can be used to implement custom decoders,
286-
for example `JSON-RPC <https://www.jsonrpc.org>`_ class hinting.
287-
Default ``None``.
288-
:type object_hook: :term:`callable` | None
289-
290-
:param object_pairs_hook:
291-
If set, a function that is called with the result of
292-
any object literal decoded with an ordered list of pairs.
293-
The return value of this function will be used
294-
instead of the :class:`dict`.
295-
This feature can be used to implement custom decoders.
296-
If *object_hook* is also set, *object_pairs_hook* takes priority.
297-
Default ``None``.
298-
:type object_pairs_hook: :term:`callable` | None
299-
300-
:param parse_float:
301-
If set, a function that is called with
302-
the string of every JSON float to be decoded.
303-
If ``None`` (the default), it is equivalent to ``float(num_str)``.
304-
This can be used to parse JSON floats into custom datatypes,
305-
for example :class:`decimal.Decimal`.
306-
:type parse_float: :term:`callable` | None
307-
308-
:param parse_int:
309-
If set, a function that is called with
310-
the string of every JSON int to be decoded.
311-
If ``None`` (the default), it is equivalent to ``int(num_str)``.
312-
This can be used to parse JSON integers into custom datatypes,
313-
for example :class:`float`.
314-
:type parse_int: :term:`callable` | None
315-
316-
:param parse_constant:
317-
If set, a function that is called with one of the following strings:
318-
``'-Infinity'``, ``'Infinity'``, or ``'NaN'``.
319-
This can be used to raise an exception
320-
if invalid JSON numbers are encountered.
321-
Default ``None``.
322-
:type parse_constant: :term:`callable` | None
323-
324-
:raises JSONDecodeError:
325-
When the data being deserialized is not a valid JSON document.
326-
327-
:raises UnicodeDecodeError:
328-
When the data being deserialized does not contain
329-
UTF-8, UTF-16 or UTF-32 encoded data.
330-
331-
.. versionchanged:: 3.1
332-
333-
* Added the optional *object_pairs_hook* parameter.
334-
* *parse_constant* doesn't get called on 'null', 'true', 'false' anymore.
335-
336-
.. versionchanged:: 3.6
337-
338-
* All optional parameters are now :ref:`keyword-only <keyword-only_parameter>`.
339-
* *fp* can now be a :term:`binary file`.
340-
The input encoding should be UTF-8, UTF-16 or UTF-32.
341-
342-
.. versionchanged:: 3.11
343-
The default *parse_int* of :func:`int` now limits the maximum length of
344-
the integer string via the interpreter's :ref:`integer string
345-
conversion length limitation <int_max_str_digits>` to help avoid denial
346-
of service attacks.
347-
348-
.. function:: loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
349-
350-
Identical to :func:`load`, but instead of a file-like object,
351-
deserialize *s* (a :class:`str`, :class:`bytes` or :class:`bytearray`
352-
instance containing a JSON document) to a Python object using this
353-
:ref:`conversion table <json-to-py-table>`.
354-
355-
.. versionchanged:: 3.6
356-
*s* can now be of type :class:`bytes` or :class:`bytearray`. The
357-
input encoding should be UTF-8, UTF-16 or UTF-32.
358-
359-
.. versionchanged:: 3.9
360-
The keyword argument *encoding* has been removed.
361-
260+
...
362261

363262
Encoders and Decoders
364263
---------------------
365264

366-
.. class:: JSONDecoder(*, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True, object_pairs_hook=None)
367-
368-
Simple JSON decoder.
369-
370-
Performs the following translations in decoding by default:
371-
372-
.. _json-to-py-table:
373-
374-
+---------------+-------------------+
375-
| JSON | Python |
376-
+===============+===================+
377-
| object | dict |
378-
+---------------+-------------------+
379-
| array | list |
380-
+---------------+-------------------+
381-
| string | str |
382-
+---------------+-------------------+
383-
| number (int) | int |
384-
+---------------+-------------------+
385-
| number (real) | float |
386-
+---------------+-------------------+
387-
| true | True |
388-
+---------------+-------------------+
389-
| false | False |
390-
+---------------+-------------------+
391-
| null | None |
392-
+---------------+-------------------+
393-
394-
It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their
395-
corresponding ``float`` values, which is outside the JSON spec.
396-
397-
*object_hook* is an optional function that will be called with the result of
398-
every JSON object decoded and its return value will be used in place of the
399-
given :class:`dict`. This can be used to provide custom deserializations
400-
(e.g. to support `JSON-RPC <https://www.jsonrpc.org>`_ class hinting).
401-
402-
*object_pairs_hook* is an optional function that will be called with the
403-
result of every JSON object decoded with an ordered list of pairs. The
404-
return value of *object_pairs_hook* will be used instead of the
405-
:class:`dict`. This feature can be used to implement custom decoders. If
406-
*object_hook* is also defined, the *object_pairs_hook* takes priority.
407-
408-
.. versionchanged:: 3.1
409-
Added support for *object_pairs_hook*.
410-
411-
*parse_float* is an optional function that will be called with the string of
412-
every JSON float to be decoded. By default, this is equivalent to
413-
``float(num_str)``. This can be used to use another datatype or parser for
414-
JSON floats (e.g. :class:`decimal.Decimal`).
415-
416-
*parse_int* is an optional function that will be called with the string of
417-
every JSON int to be decoded. By default, this is equivalent to
418-
``int(num_str)``. This can be used to use another datatype or parser for
419-
JSON integers (e.g. :class:`float`).
420-
421-
*parse_constant* is an optional function that will be called with one of the
422-
following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. This can be
423-
used to raise an exception if invalid JSON numbers are encountered.
424-
425-
If *strict* is false (``True`` is the default), then control characters
426-
will be allowed inside strings. Control characters in this context are
427-
those with character codes in the 0--31 range, including ``'\t'`` (tab),
428-
``'\n'``, ``'\r'`` and ``'\0'``.
429-
430-
If the data being deserialized is not a valid JSON document, a
431-
:exc:`JSONDecodeError` will be raised.
432-
433-
.. versionchanged:: 3.6
434-
All parameters are now :ref:`keyword-only <keyword-only_parameter>`.
435-
436-
.. method:: decode(s)
437-
438-
Return the Python representation of *s* (a :class:`str` instance
439-
containing a JSON document).
440-
441-
:exc:`JSONDecodeError` will be raised if the given JSON document is not
442-
valid.
443-
444-
.. method:: raw_decode(s)
445-
446-
Decode a JSON document from *s* (a :class:`str` beginning with a
447-
JSON document) and return a 2-tuple of the Python representation
448-
and the index in *s* where the document ended.
449-
450-
This can be used to decode a JSON document from a string that may have
451-
extraneous data at the end.
452-
453-
454-
.. class:: JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)
265+
.. class:: JSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None, arr_oneline=False)
455266

456267
Extensible JSON encoder for Python data structures.
457268

@@ -482,7 +293,7 @@ Encoders and Decoders
482293

483294
To extend this to recognize other objects, subclass and implement a
484295
:meth:`~JSONEncoder.default` method with another method that returns a serializable object
485-
for ``o`` if possible, otherwise it should call the superclass implementation
296+
for *o* if possible, otherwise it should call the superclass implementation
486297
(to raise :exc:`TypeError`).
487298

488299
If *skipkeys* is false (the default), a :exc:`TypeError` will be raised when
@@ -518,22 +329,21 @@ Encoders and Decoders
518329
.. versionchanged:: 3.2
519330
Allow strings for *indent* in addition to integers.
520331

521-
If specified, *separators* should be an ``(item_separator, key_separator)``
522-
tuple. The default is ``(', ', ': ')`` if *indent* is ``None`` and
523-
``(',', ': ')`` otherwise. To get the most compact JSON representation,
332+
If specified, *separators* should be a ``(item_separator, key_separator)``
333+
tuple. The default is ``(', ', ': ')`` if *indent* is ``None``
334+
and ``(',', ': ')`` otherwise. To get the most compact JSON representation,
524335
you should specify ``(',', ':')`` to eliminate whitespace.
525336

526337
.. versionchanged:: 3.4
527338
Use ``(',', ': ')`` as default if *indent* is not ``None``.
528339

529-
If specified, *default* should be a function that gets called for objects that
530-
can't otherwise be serialized. It should return a JSON encodable version of
531-
the object or raise a :exc:`TypeError`. If not specified, :exc:`TypeError`
532-
is raised.
533-
534-
.. versionchanged:: 3.6
535-
All parameters are now :ref:`keyword-only <keyword-only_parameter>`.
536-
340+
:param default: See :func:`dump`.
341+
:param bool arr_oneline:
342+
**New in this release.**
343+
When ``True``, JSON arrays (lists and tuples) are rendered on a single line,
344+
even if an *indent* level is specified. This option allows for a more compact
345+
representation of array data while still enabling pretty-printing of objects.
346+
Default is ``False``.
537347

538348
.. method:: default(o)
539349

@@ -572,7 +382,6 @@ Encoders and Decoders
572382
for chunk in json.JSONEncoder().iterencode(bigobject):
573383
mysocket.write(chunk)
574384

575-
576385
Exceptions
577386
----------
578387

Lib/json/__init__.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@
119119

120120
def dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True,
121121
allow_nan=True, cls=None, indent=None, separators=None,
122-
default=None, sort_keys=False, list_oneline=False, **kw):
122+
default=None, sort_keys=False, arr_oneline=False, **kw):
123123
"""Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
124124
``.write()``-supporting file-like object).
125125
@@ -155,7 +155,7 @@ def dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True,
155155
156156
If *sort_keys* is true (default: ``False``), then the output of
157157
dictionaries will be sorted by key.
158-
If *list_oneline* is true (default: ``False``), then lists/tuples will be
158+
If *arr_oneline* is true (default: ``False``), then lists/tuples will be
159159
encoded as arrays on a single line.
160160
161161
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
@@ -175,7 +175,7 @@ def dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True,
175175
iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
176176
check_circular=check_circular, allow_nan=allow_nan, indent=indent,
177177
separators=separators, default=default, sort_keys=sort_keys,
178-
list_oneline=list_oneline, **kw).iterencode(obj)
178+
arr_oneline=arr_oneline, **kw).iterencode(obj)
179179
# could accelerate with writelines in some versions of Python, at
180180
# a debuggability cost
181181
for chunk in iterable:
@@ -184,7 +184,7 @@ def dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True,
184184

185185
def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True,
186186
allow_nan=True, cls=None, indent=None, separators=None,
187-
default=None, sort_keys=False, list_oneline=False, **kw):
187+
default=None, sort_keys=False, arr_oneline=False, **kw):
188188
"""Serialize ``obj`` to a JSON formatted ``str``.
189189
190190
If ``skipkeys`` is true then ``dict`` keys that are not basic types
@@ -219,7 +219,7 @@ def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True,
219219
220220
If *sort_keys* is true (default: ``False``), then the output of
221221
dictionaries will be sorted by key.
222-
If *list_oneline* is true (default: ``False``), then lists/tuples will be
222+
If *arr_oneline* is true (default: ``False``), then lists/tuples will be
223223
encoded as arrays on a single line.
224224
225225
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
@@ -239,7 +239,7 @@ def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True,
239239
skipkeys=skipkeys, ensure_ascii=ensure_ascii,
240240
check_circular=check_circular, allow_nan=allow_nan, indent=indent,
241241
separators=separators, default=default, sort_keys=sort_keys,
242-
list_oneline=list_oneline, **kw).encode(obj)
242+
arr_oneline=arr_oneline, **kw).encode(obj)
243243

244244

245245
_default_decoder = JSONDecoder(object_hook=None, object_pairs_hook=None)

0 commit comments

Comments
 (0)