File: JSON.rst

package info (click to toggle)
python-pytooling 8.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,564 kB
  • sloc: python: 23,883; makefile: 13
file content (111 lines) | stat: -rw-r--r-- 2,164 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
.. _CONFIG/FileFormat/JSON:

JSON
****

Module :mod:`~pyTooling.Configuration.JSON` provides a configuration reader implementation for the JSON format.

.. #contents:: Table of Contents
   :local:
   :depth: 1

.. admonition:: config.json

   .. code-block:: json

      {
        "version": 1
        "list": [
          "item_1",
          "item_2"
        ],
        "dict": {
          "key_1": "value_1",
          "key_2": "value_2"
        },
        "complex": {
          "path": {
            "to": {
              "list": [
                "item_10",
                "item_11",
                "item_12"
              ],
              "dict": {
                "key_10": "value_10",
                "key_11": "value_11"
              }
            }
          }
        }
      }

.. seealso::

   ECMA Standard 404
     https://www.ecma-international.org/publications-and-standards/standards/ecma-404/
   Official JSON Website
     https://www.json.org/json-en.html
   Wikipedia
     https://en.wikipedia.org/wiki/JSON


Reading a JSON Formatted Config File
====================================

.. code-block:: python

   from pathlib import Path
   from pyTooling.Configuration.JSON import Configuration

   configFile = Path("config.json")
   config = Configuration(configFile)


Accessing Values by Name
========================

.. code-block:: python

   # root-level scalar value
   configFileFormatVersion = config["version"]

   # value in a sequence
   firstItemInList = config["list"][0]

   # first value in dictionary
   firstItemInDict = config["dict"]["key_1"]


Store Nodes in Variables
========================

.. code-block:: python

   # store intermediate node
   node = config["complex"]["path"]["to"]

   # navigate further
   nestedList = node["list"]
   nestedDict = node["dict"]


Iterate Sequences
=================

.. code-block:: python

   # simple list
   simpleList = config["list"]
   for item in simpleList:
     pass

   # deeply nested list
   nestedList = config["complex"]["path"]["to"]["list"]
   for item in nestedList:
     pass

Iterate Dictionaries
====================

.. todo:: JSON:: Needs documentation