]> begriffs open source - ai-pg/blob - full-docs/txt/datatype-json.txt
Convert HTML docs to more streamlined TXT
[ai-pg] / full-docs / txt / datatype-json.txt
1
2 8.14. JSON Types #
3
4    8.14.1. JSON Input and Output Syntax
5    8.14.2. Designing JSON Documents
6    8.14.3. jsonb Containment and Existence
7    8.14.4. jsonb Indexing
8    8.14.5. jsonb Subscripting
9    8.14.6. Transforms
10    8.14.7. jsonpath Type
11
12    JSON data types are for storing JSON (JavaScript Object Notation) data,
13    as specified in RFC 7159. Such data can also be stored as text, but the
14    JSON data types have the advantage of enforcing that each stored value
15    is valid according to the JSON rules. There are also assorted
16    JSON-specific functions and operators available for data stored in
17    these data types; see Section 9.16.
18
19    PostgreSQL offers two types for storing JSON data: json and jsonb. To
20    implement efficient query mechanisms for these data types, PostgreSQL
21    also provides the jsonpath data type described in Section 8.14.7.
22
23    The json and jsonb data types accept almost identical sets of values as
24    input. The major practical difference is one of efficiency. The json
25    data type stores an exact copy of the input text, which processing
26    functions must reparse on each execution; while jsonb data is stored in
27    a decomposed binary format that makes it slightly slower to input due
28    to added conversion overhead, but significantly faster to process,
29    since no reparsing is needed. jsonb also supports indexing, which can
30    be a significant advantage.
31
32    Because the json type stores an exact copy of the input text, it will
33    preserve semantically-insignificant white space between tokens, as well
34    as the order of keys within JSON objects. Also, if a JSON object within
35    the value contains the same key more than once, all the key/value pairs
36    are kept. (The processing functions consider the last value as the
37    operative one.) By contrast, jsonb does not preserve white space, does
38    not preserve the order of object keys, and does not keep duplicate
39    object keys. If duplicate keys are specified in the input, only the
40    last value is kept.
41
42    In general, most applications should prefer to store JSON data as
43    jsonb, unless there are quite specialized needs, such as legacy
44    assumptions about ordering of object keys.
45
46    RFC 7159 specifies that JSON strings should be encoded in UTF8. It is
47    therefore not possible for the JSON types to conform rigidly to the
48    JSON specification unless the database encoding is UTF8. Attempts to
49    directly include characters that cannot be represented in the database
50    encoding will fail; conversely, characters that can be represented in
51    the database encoding but not in UTF8 will be allowed.
52
53    RFC 7159 permits JSON strings to contain Unicode escape sequences
54    denoted by \uXXXX. In the input function for the json type, Unicode
55    escapes are allowed regardless of the database encoding, and are
56    checked only for syntactic correctness (that is, that four hex digits
57    follow \u). However, the input function for jsonb is stricter: it
58    disallows Unicode escapes for characters that cannot be represented in
59    the database encoding. The jsonb type also rejects \u0000 (because that
60    cannot be represented in PostgreSQL's text type), and it insists that
61    any use of Unicode surrogate pairs to designate characters outside the
62    Unicode Basic Multilingual Plane be correct. Valid Unicode escapes are
63    converted to the equivalent single character for storage; this includes
64    folding surrogate pairs into a single character.
65
66 Note
67
68    Many of the JSON processing functions described in Section 9.16 will
69    convert Unicode escapes to regular characters, and will therefore throw
70    the same types of errors just described even if their input is of type
71    json not jsonb. The fact that the json input function does not make
72    these checks may be considered a historical artifact, although it does
73    allow for simple storage (without processing) of JSON Unicode escapes
74    in a database encoding that does not support the represented
75    characters.
76
77    When converting textual JSON input into jsonb, the primitive types
78    described by RFC 7159 are effectively mapped onto native PostgreSQL
79    types, as shown in Table 8.23. Therefore, there are some minor
80    additional constraints on what constitutes valid jsonb data that do not
81    apply to the json type, nor to JSON in the abstract, corresponding to
82    limits on what can be represented by the underlying data type. Notably,
83    jsonb will reject numbers that are outside the range of the PostgreSQL
84    numeric data type, while json will not. Such implementation-defined
85    restrictions are permitted by RFC 7159. However, in practice such
86    problems are far more likely to occur in other implementations, as it
87    is common to represent JSON's number primitive type as IEEE 754 double
88    precision floating point (which RFC 7159 explicitly anticipates and
89    allows for). When using JSON as an interchange format with such
90    systems, the danger of losing numeric precision compared to data
91    originally stored by PostgreSQL should be considered.
92
93    Conversely, as noted in the table there are some minor restrictions on
94    the input format of JSON primitive types that do not apply to the
95    corresponding PostgreSQL types.
96
97    Table 8.23. JSON Primitive Types and Corresponding PostgreSQL Types
98    JSON primitive type PostgreSQL type Notes
99    string text \u0000 is disallowed, as are Unicode escapes representing
100    characters not available in the database encoding
101    number numeric NaN and infinity values are disallowed
102    boolean boolean Only lowercase true and false spellings are accepted
103    null (none) SQL NULL is a different concept
104
105 8.14.1. JSON Input and Output Syntax #
106
107    The input/output syntax for the JSON data types is as specified in RFC
108    7159.
109
110    The following are all valid json (or jsonb) expressions:
111 -- Simple scalar/primitive value
112 -- Primitive values can be numbers, quoted strings, true, false, or null
113 SELECT '5'::json;
114
115 -- Array of zero or more elements (elements need not be of same type)
116 SELECT '[1, 2, "foo", null]'::json;
117
118 -- Object containing pairs of keys and values
119 -- Note that object keys must always be quoted strings
120 SELECT '{"bar": "baz", "balance": 7.77, "active": false}'::json;
121
122 -- Arrays and objects can be nested arbitrarily
123 SELECT '{"foo": [true, "bar"], "tags": {"a": 1, "b": null}}'::json;
124
125    As previously stated, when a JSON value is input and then printed
126    without any additional processing, json outputs the same text that was
127    input, while jsonb does not preserve semantically-insignificant details
128    such as whitespace. For example, note the differences here:
129 SELECT '{"bar": "baz", "balance": 7.77, "active":false}'::json;
130                       json
131 -------------------------------------------------
132  {"bar": "baz", "balance": 7.77, "active":false}
133 (1 row)
134
135 SELECT '{"bar": "baz", "balance": 7.77, "active":false}'::jsonb;
136                       jsonb
137 --------------------------------------------------
138  {"bar": "baz", "active": false, "balance": 7.77}
139 (1 row)
140
141    One semantically-insignificant detail worth noting is that in jsonb,
142    numbers will be printed according to the behavior of the underlying
143    numeric type. In practice this means that numbers entered with E
144    notation will be printed without it, for example:
145 SELECT '{"reading": 1.230e-5}'::json, '{"reading": 1.230e-5}'::jsonb;
146          json          |          jsonb
147 -----------------------+-------------------------
148  {"reading": 1.230e-5} | {"reading": 0.00001230}
149 (1 row)
150
151    However, jsonb will preserve trailing fractional zeroes, as seen in
152    this example, even though those are semantically insignificant for
153    purposes such as equality checks.
154
155    For the list of built-in functions and operators available for
156    constructing and processing JSON values, see Section 9.16.
157
158 8.14.2. Designing JSON Documents #
159
160    Representing data as JSON can be considerably more flexible than the
161    traditional relational data model, which is compelling in environments
162    where requirements are fluid. It is quite possible for both approaches
163    to co-exist and complement each other within the same application.
164    However, even for applications where maximal flexibility is desired, it
165    is still recommended that JSON documents have a somewhat fixed
166    structure. The structure is typically unenforced (though enforcing some
167    business rules declaratively is possible), but having a predictable
168    structure makes it easier to write queries that usefully summarize a
169    set of “documents” (datums) in a table.
170
171    JSON data is subject to the same concurrency-control considerations as
172    any other data type when stored in a table. Although storing large
173    documents is practicable, keep in mind that any update acquires a
174    row-level lock on the whole row. Consider limiting JSON documents to a
175    manageable size in order to decrease lock contention among updating
176    transactions. Ideally, JSON documents should each represent an atomic
177    datum that business rules dictate cannot reasonably be further
178    subdivided into smaller datums that could be modified independently.
179
180 8.14.3. jsonb Containment and Existence #
181
182    Testing containment is an important capability of jsonb. There is no
183    parallel set of facilities for the json type. Containment tests whether
184    one jsonb document has contained within it another one. These examples
185    return true except as noted:
186 -- Simple scalar/primitive values contain only the identical value:
187 SELECT '"foo"'::jsonb @> '"foo"'::jsonb;
188
189 -- The array on the right side is contained within the one on the left:
190 SELECT '[1, 2, 3]'::jsonb @> '[1, 3]'::jsonb;
191
192 -- Order of array elements is not significant, so this is also true:
193 SELECT '[1, 2, 3]'::jsonb @> '[3, 1]'::jsonb;
194
195 -- Duplicate array elements don't matter either:
196 SELECT '[1, 2, 3]'::jsonb @> '[1, 2, 2]'::jsonb;
197
198 -- The object with a single pair on the right side is contained
199 -- within the object on the left side:
200 SELECT '{"product": "PostgreSQL", "version": 9.4, "jsonb": true}'::jsonb @> '{"v
201 ersion": 9.4}'::jsonb;
202
203 -- The array on the right side is not considered contained within the
204 -- array on the left, even though a similar array is nested within it:
205 SELECT '[1, 2, [1, 3]]'::jsonb @> '[1, 3]'::jsonb;  -- yields false
206
207 -- But with a layer of nesting, it is contained:
208 SELECT '[1, 2, [1, 3]]'::jsonb @> '[[1, 3]]'::jsonb;
209
210 -- Similarly, containment is not reported here:
211 SELECT '{"foo": {"bar": "baz"}}'::jsonb @> '{"bar": "baz"}'::jsonb;  -- yields f
212 alse
213
214 -- A top-level key and an empty object is contained:
215 SELECT '{"foo": {"bar": "baz"}}'::jsonb @> '{"foo": {}}'::jsonb;
216
217    The general principle is that the contained object must match the
218    containing object as to structure and data contents, possibly after
219    discarding some non-matching array elements or object key/value pairs
220    from the containing object. But remember that the order of array
221    elements is not significant when doing a containment match, and
222    duplicate array elements are effectively considered only once.
223
224    As a special exception to the general principle that the structures
225    must match, an array may contain a primitive value:
226 -- This array contains the primitive string value:
227 SELECT '["foo", "bar"]'::jsonb @> '"bar"'::jsonb;
228
229 -- This exception is not reciprocal -- non-containment is reported here:
230 SELECT '"bar"'::jsonb @> '["bar"]'::jsonb;  -- yields false
231
232    jsonb also has an existence operator, which is a variation on the theme
233    of containment: it tests whether a string (given as a text value)
234    appears as an object key or array element at the top level of the jsonb
235    value. These examples return true except as noted:
236 -- String exists as array element:
237 SELECT '["foo", "bar", "baz"]'::jsonb ? 'bar';
238
239 -- String exists as object key:
240 SELECT '{"foo": "bar"}'::jsonb ? 'foo';
241
242 -- Object values are not considered:
243 SELECT '{"foo": "bar"}'::jsonb ? 'bar';  -- yields false
244
245 -- As with containment, existence must match at the top level:
246 SELECT '{"foo": {"bar": "baz"}}'::jsonb ? 'bar'; -- yields false
247
248 -- A string is considered to exist if it matches a primitive JSON string:
249 SELECT '"foo"'::jsonb ? 'foo';
250
251    JSON objects are better suited than arrays for testing containment or
252    existence when there are many keys or elements involved, because unlike
253    arrays they are internally optimized for searching, and do not need to
254    be searched linearly.
255
256 Tip
257
258    Because JSON containment is nested, an appropriate query can skip
259    explicit selection of sub-objects. As an example, suppose that we have
260    a doc column containing objects at the top level, with most objects
261    containing tags fields that contain arrays of sub-objects. This query
262    finds entries in which sub-objects containing both "term":"paris" and
263    "term":"food" appear, while ignoring any such keys outside the tags
264    array:
265 SELECT doc->'site_name' FROM websites
266   WHERE doc @> '{"tags":[{"term":"paris"}, {"term":"food"}]}';
267
268    One could accomplish the same thing with, say,
269 SELECT doc->'site_name' FROM websites
270   WHERE doc->'tags' @> '[{"term":"paris"}, {"term":"food"}]';
271
272    but that approach is less flexible, and often less efficient as well.
273
274    On the other hand, the JSON existence operator is not nested: it will
275    only look for the specified key or array element at top level of the
276    JSON value.
277
278    The various containment and existence operators, along with all other
279    JSON operators and functions are documented in Section 9.16.
280
281 8.14.4. jsonb Indexing #
282
283    GIN indexes can be used to efficiently search for keys or key/value
284    pairs occurring within a large number of jsonb documents (datums). Two
285    GIN “operator classes” are provided, offering different performance and
286    flexibility trade-offs.
287
288    The default GIN operator class for jsonb supports queries with the
289    key-exists operators ?, ?| and ?&, the containment operator @>, and the
290    jsonpath match operators @? and @@. (For details of the semantics that
291    these operators implement, see Table 9.48.) An example of creating an
292    index with this operator class is:
293 CREATE INDEX idxgin ON api USING GIN (jdoc);
294
295    The non-default GIN operator class jsonb_path_ops does not support the
296    key-exists operators, but it does support @>, @? and @@. An example of
297    creating an index with this operator class is:
298 CREATE INDEX idxginp ON api USING GIN (jdoc jsonb_path_ops);
299
300    Consider the example of a table that stores JSON documents retrieved
301    from a third-party web service, with a documented schema definition. A
302    typical document is:
303 {
304     "guid": "9c36adc1-7fb5-4d5b-83b4-90356a46061a",
305     "name": "Angela Barton",
306     "is_active": true,
307     "company": "Magnafone",
308     "address": "178 Howard Place, Gulf, Washington, 702",
309     "registered": "2009-11-07T08:53:22 +08:00",
310     "latitude": 19.793713,
311     "longitude": 86.513373,
312     "tags": [
313         "enim",
314         "aliquip",
315         "qui"
316     ]
317 }
318
319    We store these documents in a table named api, in a jsonb column named
320    jdoc. If a GIN index is created on this column, queries like the
321    following can make use of the index:
322 -- Find documents in which the key "company" has value "Magnafone"
323 SELECT jdoc->'guid', jdoc->'name' FROM api WHERE jdoc @> '{"company": "Magnafone
324 "}';
325
326    However, the index could not be used for queries like the following,
327    because though the operator ? is indexable, it is not applied directly
328    to the indexed column jdoc:
329 -- Find documents in which the key "tags" contains key or array element "qui"
330 SELECT jdoc->'guid', jdoc->'name' FROM api WHERE jdoc -> 'tags' ? 'qui';
331
332    Still, with appropriate use of expression indexes, the above query can
333    use an index. If querying for particular items within the "tags" key is
334    common, defining an index like this may be worthwhile:
335 CREATE INDEX idxgintags ON api USING GIN ((jdoc -> 'tags'));
336
337    Now, the WHERE clause jdoc -> 'tags' ? 'qui' will be recognized as an
338    application of the indexable operator ? to the indexed expression jdoc
339    -> 'tags'. (More information on expression indexes can be found in
340    Section 11.7.)
341
342    Another approach to querying is to exploit containment, for example:
343 -- Find documents in which the key "tags" contains array element "qui"
344 SELECT jdoc->'guid', jdoc->'name' FROM api WHERE jdoc @> '{"tags": ["qui"]}';
345
346    A simple GIN index on the jdoc column can support this query. But note
347    that such an index will store copies of every key and value in the jdoc
348    column, whereas the expression index of the previous example stores
349    only data found under the tags key. While the simple-index approach is
350    far more flexible (since it supports queries about any key), targeted
351    expression indexes are likely to be smaller and faster to search than a
352    simple index.
353
354    GIN indexes also support the @? and @@ operators, which perform
355    jsonpath matching. Examples are
356 SELECT jdoc->'guid', jdoc->'name' FROM api WHERE jdoc @? '$.tags[*] ? (@ == "qui
357 ")';
358
359 SELECT jdoc->'guid', jdoc->'name' FROM api WHERE jdoc @@ '$.tags[*] == "qui"';
360
361    For these operators, a GIN index extracts clauses of the form
362    accessors_chain == constant out of the jsonpath pattern, and does the
363    index search based on the keys and values mentioned in these clauses.
364    The accessors chain may include .key, [*], and [index] accessors. The
365    jsonb_ops operator class also supports .* and .** accessors, but the
366    jsonb_path_ops operator class does not.
367
368    Although the jsonb_path_ops operator class supports only queries with
369    the @>, @? and @@ operators, it has notable performance advantages over
370    the default operator class jsonb_ops. A jsonb_path_ops index is usually
371    much smaller than a jsonb_ops index over the same data, and the
372    specificity of searches is better, particularly when queries contain
373    keys that appear frequently in the data. Therefore search operations
374    typically perform better than with the default operator class.
375
376    The technical difference between a jsonb_ops and a jsonb_path_ops GIN
377    index is that the former creates independent index items for each key
378    and value in the data, while the latter creates index items only for
379    each value in the data. ^[7] Basically, each jsonb_path_ops index item
380    is a hash of the value and the key(s) leading to it; for example to
381    index {"foo": {"bar": "baz"}}, a single index item would be created
382    incorporating all three of foo, bar, and baz into the hash value. Thus
383    a containment query looking for this structure would result in an
384    extremely specific index search; but there is no way at all to find out
385    whether foo appears as a key. On the other hand, a jsonb_ops index
386    would create three index items representing foo, bar, and baz
387    separately; then to do the containment query, it would look for rows
388    containing all three of these items. While GIN indexes can perform such
389    an AND search fairly efficiently, it will still be less specific and
390    slower than the equivalent jsonb_path_ops search, especially if there
391    are a very large number of rows containing any single one of the three
392    index items.
393
394    A disadvantage of the jsonb_path_ops approach is that it produces no
395    index entries for JSON structures not containing any values, such as
396    {"a": {}}. If a search for documents containing such a structure is
397    requested, it will require a full-index scan, which is quite slow.
398    jsonb_path_ops is therefore ill-suited for applications that often
399    perform such searches.
400
401    jsonb also supports btree and hash indexes. These are usually useful
402    only if it's important to check equality of complete JSON documents.
403    The btree ordering for jsonb datums is seldom of great interest, but
404    for completeness it is:
405 Object > Array > Boolean > Number > String > null
406
407 Object with n pairs > object with n - 1 pairs
408
409 Array with n elements > array with n - 1 elements
410
411    with the exception that (for historical reasons) an empty top level
412    array sorts less than null. Objects with equal numbers of pairs are
413    compared in the order:
414 key-1, value-1, key-2 ...
415
416    Note that object keys are compared in their storage order; in
417    particular, since shorter keys are stored before longer keys, this can
418    lead to results that might be unintuitive, such as:
419 { "aa": 1, "c": 1} > {"b": 1, "d": 1}
420
421    Similarly, arrays with equal numbers of elements are compared in the
422    order:
423 element-1, element-2 ...
424
425    Primitive JSON values are compared using the same comparison rules as
426    for the underlying PostgreSQL data type. Strings are compared using the
427    default database collation.
428
429 8.14.5. jsonb Subscripting #
430
431    The jsonb data type supports array-style subscripting expressions to
432    extract and modify elements. Nested values can be indicated by chaining
433    subscripting expressions, following the same rules as the path argument
434    in the jsonb_set function. If a jsonb value is an array, numeric
435    subscripts start at zero, and negative integers count backwards from
436    the last element of the array. Slice expressions are not supported. The
437    result of a subscripting expression is always of the jsonb data type.
438
439    UPDATE statements may use subscripting in the SET clause to modify
440    jsonb values. Subscript paths must be traversable for all affected
441    values insofar as they exist. For instance, the path val['a']['b']['c']
442    can be traversed all the way to c if every val, val['a'], and
443    val['a']['b'] is an object. If any val['a'] or val['a']['b'] is not
444    defined, it will be created as an empty object and filled as necessary.
445    However, if any val itself or one of the intermediary values is defined
446    as a non-object such as a string, number, or jsonb null, traversal
447    cannot proceed so an error is raised and the transaction aborted.
448
449    An example of subscripting syntax:
450
451 -- Extract object value by key
452 SELECT ('{"a": 1}'::jsonb)['a'];
453
454 -- Extract nested object value by key path
455 SELECT ('{"a": {"b": {"c": 1}}}'::jsonb)['a']['b']['c'];
456
457 -- Extract array element by index
458 SELECT ('[1, "2", null]'::jsonb)[1];
459
460 -- Update object value by key. Note the quotes around '1': the assigned
461 -- value must be of the jsonb type as well
462 UPDATE table_name SET jsonb_field['key'] = '1';
463
464 -- This will raise an error if any record's jsonb_field['a']['b'] is something
465 -- other than an object. For example, the value {"a": 1} has a numeric value
466 -- of the key 'a'.
467 UPDATE table_name SET jsonb_field['a']['b']['c'] = '1';
468
469 -- Filter records using a WHERE clause with subscripting. Since the result of
470 -- subscripting is jsonb, the value we compare it against must also be jsonb.
471 -- The double quotes make "value" also a valid jsonb string.
472 SELECT * FROM table_name WHERE jsonb_field['key'] = '"value"';
473
474    jsonb assignment via subscripting handles a few edge cases differently
475    from jsonb_set. When a source jsonb value is NULL, assignment via
476    subscripting will proceed as if it was an empty JSON value of the type
477    (object or array) implied by the subscript key:
478 -- Where jsonb_field was NULL, it is now {"a": 1}
479 UPDATE table_name SET jsonb_field['a'] = '1';
480
481 -- Where jsonb_field was NULL, it is now [1]
482 UPDATE table_name SET jsonb_field[0] = '1';
483
484    If an index is specified for an array containing too few elements, NULL
485    elements will be appended until the index is reachable and the value
486    can be set.
487 -- Where jsonb_field was [], it is now [null, null, 2];
488 -- where jsonb_field was [0], it is now [0, null, 2]
489 UPDATE table_name SET jsonb_field[2] = '2';
490
491    A jsonb value will accept assignments to nonexistent subscript paths as
492    long as the last existing element to be traversed is an object or
493    array, as implied by the corresponding subscript (the element indicated
494    by the last subscript in the path is not traversed and may be
495    anything). Nested array and object structures will be created, and in
496    the former case null-padded, as specified by the subscript path until
497    the assigned value can be placed.
498 -- Where jsonb_field was {}, it is now {"a": [{"b": 1}]}
499 UPDATE table_name SET jsonb_field['a'][0]['b'] = '1';
500
501 -- Where jsonb_field was [], it is now [null, {"a": 1}]
502 UPDATE table_name SET jsonb_field[1]['a'] = '1';
503
504 8.14.6. Transforms #
505
506    Additional extensions are available that implement transforms for the
507    jsonb type for different procedural languages.
508
509    The extensions for PL/Perl are called jsonb_plperl and jsonb_plperlu.
510    If you use them, jsonb values are mapped to Perl arrays, hashes, and
511    scalars, as appropriate.
512
513    The extension for PL/Python is called jsonb_plpython3u. If you use it,
514    jsonb values are mapped to Python dictionaries, lists, and scalars, as
515    appropriate.
516
517    Of these extensions, jsonb_plperl is considered “trusted”, that is, it
518    can be installed by non-superusers who have CREATE privilege on the
519    current database. The rest require superuser privilege to install.
520
521 8.14.7. jsonpath Type #
522
523    The jsonpath type implements support for the SQL/JSON path language in
524    PostgreSQL to efficiently query JSON data. It provides a binary
525    representation of the parsed SQL/JSON path expression that specifies
526    the items to be retrieved by the path engine from the JSON data for
527    further processing with the SQL/JSON query functions.
528
529    The semantics of SQL/JSON path predicates and operators generally
530    follow SQL. At the same time, to provide a natural way of working with
531    JSON data, SQL/JSON path syntax uses some JavaScript conventions:
532      * Dot (.) is used for member access.
533      * Square brackets ([]) are used for array access.
534      * SQL/JSON arrays are 0-relative, unlike regular SQL arrays that
535        start from 1.
536
537    Numeric literals in SQL/JSON path expressions follow JavaScript rules,
538    which are different from both SQL and JSON in some minor details. For
539    example, SQL/JSON path allows .1 and 1., which are invalid in JSON.
540    Non-decimal integer literals and underscore separators are supported,
541    for example, 1_000_000, 0x1EEE_FFFF, 0o273, 0b100101. In SQL/JSON path
542    (and in JavaScript, but not in SQL proper), there must not be an
543    underscore separator directly after the radix prefix.
544
545    An SQL/JSON path expression is typically written in an SQL query as an
546    SQL character string literal, so it must be enclosed in single quotes,
547    and any single quotes desired within the value must be doubled (see
548    Section 4.1.2.1). Some forms of path expressions require string
549    literals within them. These embedded string literals follow
550    JavaScript/ECMAScript conventions: they must be surrounded by double
551    quotes, and backslash escapes may be used within them to represent
552    otherwise-hard-to-type characters. In particular, the way to write a
553    double quote within an embedded string literal is \", and to write a
554    backslash itself, you must write \\. Other special backslash sequences
555    include those recognized in JavaScript strings: \b, \f, \n, \r, \t, \v
556    for various ASCII control characters, \xNN for a character code written
557    with only two hex digits, \uNNNN for a Unicode character identified by
558    its 4-hex-digit code point, and \u{N...} for a Unicode character code
559    point written with 1 to 6 hex digits.
560
561    A path expression consists of a sequence of path elements, which can be
562    any of the following:
563      * Path literals of JSON primitive types: Unicode text, numeric, true,
564        false, or null.
565      * Path variables listed in Table 8.24.
566      * Accessor operators listed in Table 8.25.
567      * jsonpath operators and methods listed in Section 9.16.2.3.
568      * Parentheses, which can be used to provide filter expressions or
569        define the order of path evaluation.
570
571    For details on using jsonpath expressions with SQL/JSON query
572    functions, see Section 9.16.2.
573
574    Table 8.24. jsonpath Variables
575    Variable Description
576    $ A variable representing the JSON value being queried (the context
577    item).
578    $varname A named variable. Its value can be set by the parameter vars
579    of several JSON processing functions; see Table 9.51 for details.
580    @ A variable representing the result of path evaluation in filter
581    expressions.
582
583    Table 8.25. jsonpath Accessors
584    Accessor Operator Description
585
586    .key
587
588    ."$varname"
589
590    Member accessor that returns an object member with the specified key.
591    If the key name matches some named variable starting with $ or does not
592    meet the JavaScript rules for an identifier, it must be enclosed in
593    double quotes to make it a string literal.
594
595    .*
596
597    Wildcard member accessor that returns the values of all members located
598    at the top level of the current object.
599
600    .**
601
602    Recursive wildcard member accessor that processes all levels of the
603    JSON hierarchy of the current object and returns all the member values,
604    regardless of their nesting level. This is a PostgreSQL extension of
605    the SQL/JSON standard.
606
607    .**{level}
608
609    .**{start_level to end_level}
610
611    Like .**, but selects only the specified levels of the JSON hierarchy.
612    Nesting levels are specified as integers. Level zero corresponds to the
613    current object. To access the lowest nesting level, you can use the
614    last keyword. This is a PostgreSQL extension of the SQL/JSON standard.
615
616    [subscript, ...]
617
618    Array element accessor. subscript can be given in two forms: index or
619    start_index to end_index. The first form returns a single array element
620    by its index. The second form returns an array slice by the range of
621    indexes, including the elements that correspond to the provided
622    start_index and end_index.
623
624    The specified index can be an integer, as well as an expression
625    returning a single numeric value, which is automatically cast to
626    integer. Index zero corresponds to the first array element. You can
627    also use the last keyword to denote the last array element, which is
628    useful for handling arrays of unknown length.
629
630    [*]
631
632    Wildcard array element accessor that returns all array elements.
633
634    ^[7] For this purpose, the term “value” includes array elements, though
635    JSON terminology sometimes considers array elements distinct from
636    values within objects.