バージョンごとのドキュメント一覧

9.16. JSON関数と演算子 #

<title>JSON Functions and Operators</title>

This section describes: この節では次のことを説明します。

To provide native support for JSON data types within the SQL environment, <productname>PostgreSQL</productname> implements the <firstterm>SQL/JSON data model</firstterm>. This model comprises sequences of items. Each item can hold SQL scalar values, with an additional SQL/JSON null value, and composite data structures that use JSON arrays and objects. The model is a formalization of the implied data model in the JSON specification <ulink url="https://tools.ietf.org/html/rfc7159">RFC 7159</ulink>. SQL環境内のJSONデータ型にネイティブサポートを提供するために、PostgreSQLSQL/JSONデータモデルを実装しています。 このモデルは、一連の項目で構成されます。 各項目は、SQLスカラ値、追加のSQL/JSON NULL値、およびJSON配列とオブジェクトを使用する複合データ構造を保持できます。 モデルは、JSON指定RFC 7159で暗黙的に指定されているデータモデルを形式化したものです

SQL/JSON allows you to handle JSON data alongside regular SQL data, with transaction support, including: SQL/JSONでは、トランザクションをサポートをしながら、通常のSQLデータと一緒にJSONデータをハンドルすることができます。以下のものが含まれます:

To learn more about the SQL/JSON standard, see <xref linkend="sqltr-19075-6"/>. For details on JSON types supported in <productname>PostgreSQL</productname>, see <xref linkend="datatype-json"/>. SQL/JSON標準を更に学ぶためには、[sqltr-19075-6]をご覧ください。 PostgreSQLでサポートされているJSON型の詳細に関しては、8.14をご覧ください。

9.16.1. JSONデータの処理と生成 #

<title>Processing and Creating JSON Data</title>

<xref linkend="functions-json-op-table"/> shows the operators that are available for use with JSON data types (see <xref linkend="datatype-json"/>). In addition, the usual comparison operators shown in <xref linkend="functions-comparison-op-table"/> are available for <type>jsonb</type>, though not for <type>json</type>. The comparison operators follow the ordering rules for B-tree operations outlined in <xref linkend="json-indexing"/>. See also <xref linkend="functions-aggregate"/> for the aggregate function <function>json_agg</function> which aggregates record values as JSON, the aggregate function <function>json_object_agg</function> which aggregates pairs of values into a JSON object, and their <type>jsonb</type> equivalents, <function>jsonb_agg</function> and <function>jsonb_object_agg</function>. 表 9.45にJSONデータ型(8.14を参照)で使用可能な演算子を示します。 加えて表 9.1で示す通常の比較演算子がjsonbで利用できますが、jsonでは利用できません。 比較演算子は8.14.4で概要が示されているように示すBツリー操作用の順序付け規則にしたがいます。 レコードの値をJSONに集約するjson_agg集約関数、値の対をJSONオブジェクトに集約するjson_object_agg集約関数、およびそれらのjsonb版のjsonb_aggjsonb_object_aggについては9.21も参照して下さい。

表9.45 jsonjsonb演算子

<title><type>json</type> and <type>jsonb</type> Operators</title>

Operator 演算子

Description 説明

Example(s)

json -> integerjson

jsonb -> integerjsonb

Extracts <parameter>n</parameter>'th element of JSON array (array elements are indexed from zero, but negative integers count from the end). JSON配列のn番目の要素を取り出します。 (配列要素はゼロから始まりますが、負の整数は最後から数えられます。)

'[{"a":"foo"},{"b":"bar"},{"c":"baz"}]'::json -> 2{"c":"baz"}

'[{"a":"foo"},{"b":"bar"},{"c":"baz"}]'::json -> -3{"a":"foo"}

json -> textjson

jsonb -> textjsonb

Extracts JSON object field with the given key. 与えられたキーでJSONオブジェクトフィールドを取り出します。

'{"a": {"b":"foo"}}'::json -> 'a'{"b":"foo"}

json ->> integertext

jsonb ->> integertext

Extracts <parameter>n</parameter>'th element of JSON array, as <type>text</type>. JSON配列のn番目の要素をtextとして取り出します。

'[1,2,3]'::json ->> 23

json ->> texttext

jsonb ->> texttext

Extracts JSON object field with the given key, as <type>text</type>. 与えられたキーでJSONオブジェクトフィールドをtextとして取り出します。

'{"a":1,"b":2}'::json ->> 'b'2

json #> text[]json

jsonb #> text[]jsonb

Extracts JSON sub-object at the specified path, where path elements can be either field keys or array indexes. 指定したパスにおけるJSONの副オブジェクトを取り出します。パス要素はフィールドキーあるいは配列のインデックスでも構いません。

'{"a": {"b": ["foo","bar"]}}'::json #> '{a,b,1}'"bar"

json #>> text[]text

jsonb #>> text[]text

Extracts JSON sub-object at the specified path as <type>text</type>. 指定したパスにおけるJSONの副オブジェクトをtextとして取り出します。

'{"a": {"b": ["foo","bar"]}}'::json #>> '{a,b,1}'bar


注記

The field/element/path extraction operators return NULL, rather than failing, if the JSON input does not have the right structure to match the request; for example if no such key or array element exists. JSON入力が要求と一致する正しい構造をしていなければ、フィールド/要素/パス抽出演算子は失敗するのではなくNULLを返します。例えばそのような要素が存在しない場合です。

Some further operators exist only for <type>jsonb</type>, as shown in <xref linkend="functions-jsonb-op-table"/>. <xref linkend="json-indexing"/> describes how these operators can be used to effectively search indexed <type>jsonb</type> data. ほかにjsonbだけで利用可能な演算子もいくつか存在します。 それらを表 9.46に示します。 8.14.4には、インデックス付されたjsonbデータを効率的に検索するためにこれらの演算子をどのように利用できるかについて書いてあります。

表9.46 追加jsonb演算子

<title>Additional <type>jsonb</type> Operators</title>

Operator 演算子

Description 説明

Example(s)

jsonb @> jsonbboolean

Does the first JSON value contain the second? (See <xref linkend="json-containment"/> for details about containment.) 最初のJSON値は二番目を含んでいるか? (包含の詳細は8.14.3を参照してください。)

'{"a":1, "b":2}'::jsonb @> '{"b":2}'::jsonbt

jsonb <@ jsonbboolean

Is the first JSON value contained in the second? 最初のJSON値は二番目に含まれているか?

'{"b":2}'::jsonb <@ '{"a":1, "b":2}'::jsonbt

jsonb ? textboolean

Does the text string exist as a top-level key or array element within the JSON value? そのテキスト文字列はトップレベルのキーあるいは配列要素としてJSON値中に存在しているか?

'{"a":1, "b":2}'::jsonb ? 'b't

'["a", "b", "c"]'::jsonb ? 'b't

jsonb ?| text[]boolean

Do any of the strings in the text array exist as top-level keys or array elements? テキスト配列中のどれかの文字列がトップレベルのキーあるいは配列要素として存在しているか?

'{"a":1, "b":2, "c":3}'::jsonb ?| array['b', 'd']t

jsonb ?& text[]boolean

Do all of the strings in the text array exist as top-level keys or array elements? テキスト配列のすべての文字列がトップレベルのキーあるいは配列要素として存在しているか?

'["a", "b", "c"]'::jsonb ?& array['a', 'b']t

jsonb || jsonbjsonb

Concatenates two <type>jsonb</type> values. Concatenating two arrays generates an array containing all the elements of each input. Concatenating two objects generates an object containing the union of their keys, taking the second object's value when there are duplicate keys. All other cases are treated by converting a non-array input into a single-element array, and then proceeding as for two arrays. Does not operate recursively: only the top-level array or object structure is merged. 2つのjsonb値を結合します。 2つの配列を結合するとそれらのキーの和を持つ配列を生成します。 キーが重複している場合は2番目のオブジェクトの値が使用されます。 それ以外の場合には非配列入力を単一の要素を持つ配列に変換し、次に2つの配列として取り扱います。 再帰操作は行いません。トップレベルの配列あるいはオブジェクト構造だけがマージされます。

'["a", "b"]'::jsonb || '["a", "d"]'::jsonb["a", "b", "a", "d"]

'{"a": "b"}'::jsonb || '{"c": "d"}'::jsonb{"a": "b", "c": "d"}

'[1, 2]'::jsonb || '3'::jsonb[1, 2, 3]

'{"a": "b"}'::jsonb || '42'::jsonb[{"a": "b"}, 42]

To append an array to another array as a single entry, wrap it in an additional layer of array, for example: 一つの要素を持つとして配列を他の配列に追加するには、例のように配列の追加のレイヤー中に含めてください。

'[1, 2]'::jsonb || jsonb_build_array('[3, 4]'::jsonb)[1, 2, [3, 4]]

jsonb - textjsonb

Deletes a key (and its value) from a JSON object, or matching string value(s) from a JSON array. キー(及びその値)をJSONオブジェクトから削除します。あるいはマッチする文字列値をJSON配列から削除します。

'{"a": "b", "c": "d"}'::jsonb - 'a'{"c": "d"}

'["a", "b", "c", "b"]'::jsonb - 'b'["a", "c"]

jsonb - text[]jsonb

Deletes all matching keys or array elements from the left operand. 左のオペランドからマッチするすべてのキーあるいは配列要素を削除します。

'{"a": "b", "c": "d"}'::jsonb - '{a,c}'::text[]{}

jsonb - integerjsonb

Deletes the array element with specified index (negative integers count from the end). Throws an error if JSON value is not an array. 指定したインデックス(負の整数は最後から数えます)の配列要素を削除します。 JSON値が配列でなければエラーが生じます。

'["a", "b"]'::jsonb - 1 ["a"]

jsonb #- text[]jsonb

Deletes the field or array element at the specified path, where path elements can be either field keys or array indexes. 指定パスのフィールドあるいは配列要素を削除します。パス要素はフィールドキーあるいは配列インデックスが指定できます。

'["a", {"b":1}]'::jsonb #- '{1,b}'["a", {}]

jsonb @? jsonpathboolean

Does JSON path return any item for the specified JSON value? JSONパスは指定したJSON値の要素を返すか?

'{"a":[1,2,3,4,5]}'::jsonb @? '$.a[*] ? (@ > 2)'t

jsonb @@ jsonpathboolean

Returns the result of a JSON path predicate check for the specified JSON value. Only the first item of the result is taken into account. If the result is not Boolean, then <literal>NULL</literal> is returned. 指定したJSON値に対するJSONパス述語チェックの結果を返します。 結果の最初の項目だけが考慮されます。 結果が論理値でなければNULLが返ります。

'{"a":[1,2,3,4,5]}'::jsonb @@ '$.a[*] > 2't


注記

The <type>jsonpath</type> operators <literal>@?</literal> and <literal>@@</literal> suppress the following errors: missing object field or array element, unexpected JSON item type, datetime and numeric errors. The <type>jsonpath</type>-related functions described below can also be told to suppress these types of errors. This behavior might be helpful when searching JSON document collections of varying structure. jsonpath演算子の@?および@@演算子は以下のエラーを抑止します。 オブジェクトフィールドあるいは配列要素の欠如、期待しないJSON要素型、日付時刻及び数値エラー。 以下に示すjsonpath関連の関数もこれらのエラーを抑止するようにすることもできます。 この振る舞いは、異なる構造のJSON文書集合を検索する際に役に立つかも知れません。

<xref linkend="functions-json-creation-table"/> shows the functions that are available for constructing <type>json</type> and <type>jsonb</type> values. 表 9.47に、json値およびjsonb値を作成するために利用可能な関数を示します。 Some functions in this table have a <literal>RETURNING</literal> clause, which specifies the data type returned. It must be one of <type>json</type>, <type>jsonb</type>, <type>bytea</type>, a character string type (<type>text</type>, <type>char</type>, <type>varchar</type>, or <type>nchar</type>), or a type for which there is a cast from <type>json</type> to that type. By default, the <type>json</type> type is returned. このテーブルのいくつかの関数は、返却データ型を指定するRETURNING句を伴います。 そのデータ型は、jsonjsonbbytea、文字列型(textcharvarcharnchar)、あるいはjsonからそれらの型へのキャストが存在する型でなければなりません。 デフォルトでは、json型が返却されます。

表9.47 JSON作成関数

<title>JSON Creation Functions</title>

Function 関数

Description 説明

Example(s)

to_json ( anyelement ) → json

to_jsonb ( anyelement ) → jsonb

Converts any SQL value to <type>json</type> or <type>jsonb</type>. Arrays and composites are converted recursively to arrays and objects (multidimensional arrays become arrays of arrays in JSON). Otherwise, if there is a cast from the SQL data type to <type>json</type>, the cast function will be used to perform the conversion;<footnote> SQL値をjsonあるいはjsonbに変換します。 配列と複合型は再帰的に配列とオブジェクトに変換されます。(多次元配列はJSONにおける配列の配列になります。) それ以外は、そのSQLデータ型からjsonにキャストがあれば、キャスト関数が変換のために用いられます。[a] otherwise, a scalar JSON value is produced. For any scalar other than a number, a Boolean, or a null value, the text representation will be used, with escaping as necessary to make it a valid JSON string value. そうでなければスカラーJSON値が生成されます。 数値、論理値、NULL以外のスカラーには、有効なJSON文字列値にするための必要なエスケープ処理が施されたテキスト表現が使われます。

to_json('Fred said "Hi."'::text)"Fred said \"Hi.\""

to_jsonb(row(42, 'Fred said "Hi."'::text)){"f1": 42, "f2": "Fred said \"Hi.\""}

array_to_json ( anyarray [, boolean ] ) → json

Converts an SQL array to a JSON array. The behavior is the same as <function>to_json</function> except that line feeds will be added between top-level array elements if the optional boolean parameter is true. SQL配列をJSON配列に変換します。 追加の論理引数が真であるときに改行がトップレベルの配列要素の間に加えられる以外は、その振る舞いはto_jsonと同じです。

array_to_json('{{1,5},{99,100}}'::int[])[[1,5],[99,100]]

json_array ( [ { value_expression [ FORMAT JSON ] } [, ...] ] [ { NULL | ABSENT } ON NULL ] [ RETURNING data_type [ FORMAT JSON [ ENCODING UTF8 ] ] ])

json_array ( [ query_expression ] [ RETURNING data_type [ FORMAT JSON [ ENCODING UTF8 ] ] ])

Constructs a JSON array from either a series of <replaceable>value_expression</replaceable> parameters or from the results of <replaceable>query_expression</replaceable>, which must be a SELECT query returning a single column. If <literal>ABSENT ON NULL</literal> is specified, NULL values are ignored. This is always the case if a <replaceable>query_expression</replaceable> is used. JSON配列を、一連のvalue_expression引数、またはquery_expressionの結果のいずれかから構成します。 query_expressionは、単一の列を返すSELECT問い合わせである必要があります。 ABSENT ON NULLが指定されている場合、NULL値は無視されます。 query_expressionが使用されている場合、常にそうなります。

json_array(1,true,json '{"a":null}')[1, true, {"a":null}]

json_array(SELECT * FROM (VALUES(1),(2)) t)[1, 2]

row_to_json ( record [, boolean ] ) → json

Converts an SQL composite value to a JSON object. The behavior is the same as <function>to_json</function> except that line feeds will be added between top-level elements if the optional boolean parameter is true. SQL複合値をJSONオブジェクトに変換します。 追加の論理引数が真であるときに改行がトップレベルの配列要素の間に加えられる以外は、その振る舞いはto_jsonと同じです。

row_to_json(row(1,'foo')){"f1":1,"f2":"foo"}

json_build_array ( VARIADIC "any" ) → json

jsonb_build_array ( VARIADIC "any" ) → jsonb

Builds a possibly-heterogeneously-typed JSON array out of a variadic argument list. Each argument is converted as per <function>to_json</function> or <function>to_jsonb</function>. 異なる型から構成される可能性のあるJSON配列をvariadic引数リストから作成します。 各々の引数はto_jsonあるいはto_jsonbに従って変換されます。

json_build_array(1, 2, 'foo', 4, 5)[1, 2, "foo", 4, 5]

json_build_object ( VARIADIC "any" ) → json

jsonb_build_object ( VARIADIC "any" ) → jsonb

Builds a JSON object out of a variadic argument list. By convention, the argument list consists of alternating keys and values. Key arguments are coerced to text; value arguments are converted as per <function>to_json</function> or <function>to_jsonb</function>. variadic引数リストからJSONオブジェクトを作成します。 慣例により引数リストは代替キーと値が交互に並んだものです。 キー引数はテキストに強制的に変換されます。 値引数はto_jsonあるいはto_jsonbに従って変換されます。

json_build_object('foo', 1, 2, row(3,'bar')){"foo" : 1, "2" : {"f1":3,"f2":"bar"}}

json_object ( [ { key_expression { VALUE | ':' } value_expression [ FORMAT JSON [ ENCODING UTF8 ] ] }[, ...] ] [ { NULL | ABSENT } ON NULL ] [ { WITH | WITHOUT } UNIQUE [ KEYS ] ] [ RETURNING data_type [ FORMAT JSON [ ENCODING UTF8 ] ] ])

Constructs a JSON object of all the key/value pairs given, or an empty object if none are given. <replaceable>key_expression</replaceable> is a scalar expression defining the <acronym>JSON</acronym> key, which is converted to the <type>text</type> type. It cannot be <literal>NULL</literal> nor can it belong to a type that has a cast to the <type>json</type> type. If <literal>WITH UNIQUE KEYS</literal> is specified, there must not be any duplicate <replaceable>key_expression</replaceable>. Any pair for which the <replaceable>value_expression</replaceable> evaluates to <literal>NULL</literal> is omitted from the output if <literal>ABSENT ON NULL</literal> is specified; if <literal>NULL ON NULL</literal> is specified or the clause omitted, the key is included with value <literal>NULL</literal>. 指定されたすべてのキー/値ペアのJSONオブジェクトを構築します。 キー/値ペアが指定されていない場合は、空のオブジェクトを構築します。 key_expressionは、textタイプに変換されるJSONキーを定義するスカラ式です。 NULLにすることも、JSONタイプにキャストを持つタイプに属することもできません。 WITH UNIQUE KEYSが指定されている場合は、重複key_expressionがあってはなりません。 ABSENT ON NULLが指定されている場合、NULLと評価されるvalue_expressionは出力から除外されます。 NULL ON NULLが指定されているか、その指定が省略されている場合、NULL値のキーが含まれます。

json_object('code' VALUE 'P123', 'title': 'Jaws'){"code" : "P123", "title" : "Jaws"}

json_object ( text[] ) → json

jsonb_object ( text[] ) → jsonb

Builds a JSON object out of a text array. The array must have either exactly one dimension with an even number of members, in which case they are taken as alternating key/value pairs, or two dimensions such that each inner array has exactly two elements, which are taken as a key/value pair. All values are converted to JSON strings. テキスト配列からJSONオブジェクトを作成します。 配列は、偶数個の要素からなる1次元(キー/値の対が交互に並んでいるものと扱われます)あるいは内側の配列が2つの要素を持つ2次元(2つの要素がキー/値のペアとして扱われます)のいずれかでなければなりません。 すべての値はJSON文字列に変換されます。

json_object('{a, 1, b, "def", c, 3.5}'){"a" : "1", "b" : "def", "c" : "3.5"}

json_object('{{a, 1}, {b, "def"}, {c, 3.5}}'){"a" : "1", "b" : "def", "c" : "3.5"}

json_object ( keys text[], values text[] ) → json

jsonb_object ( keys text[], values text[] ) → jsonb

This form of <function>json_object</function> takes keys and values pairwise from separate text arrays. Otherwise it is identical to the one-argument form. この形のjson_objectは2つの別々の配列からキーと値の対を取ります。 他の点ではすべて、引数1つの形と同じです。

json_object('{a,b}', '{1,2}'){"a": "1", "b": "2"}

[a] For example, the <xref linkend="hstore"/> extension has a cast from <type>hstore</type> to <type>json</type>, so that <type>hstore</type> values converted via the JSON creation functions will be represented as JSON objects, not as primitive string values. たとえばhstore拡張にはhstoreからjsonへのキャストがあり、JSON生成関数で変換されたhstore値は、原始的な文字列値としてではなく、JSONオブジェクトとして表示されます。


<xref linkend="functions-sqljson-misc" /> details SQL/JSON facilities for testing JSON. 表 9.48には、JSONをテストするためのSQL/JSON機能の詳細が記載されています。

表9.48 SQL/JSONテスト用関数

<title>SQL/JSON Testing Functions</title>

Function signature 関数の呼び出し形式

Description 説明

Example(s)

expression IS [ NOT ] JSON [ { VALUE | SCALAR | ARRAY | OBJECT } ] [ { WITH | WITHOUT } UNIQUE [ KEYS ] ]

This predicate tests whether <replaceable>expression</replaceable> can be parsed as JSON, possibly of a specified type. If <literal>SCALAR</literal> or <literal>ARRAY</literal> or <literal>OBJECT</literal> is specified, the test is whether or not the JSON is of that particular type. If <literal>WITH UNIQUE KEYS</literal> is specified, then any object in the <replaceable>expression</replaceable> is also tested to see if it has duplicate keys. この述語は、expressionが指定された型のJSONとして解析できるかどうかをテストします。 SCALARARRAY、またはOBJECTが指定されている場合、テストはJSONがその特定の型のものであるかどうかを示します。 WITH UNIQUE KEYSが指定されている場合、expressionのオブジェクトもテストされ、重複キーがあるかどうかが確認されます。

SELECT js,
  js IS JSON "json?",
  js IS JSON SCALAR "scalar?",
  js IS JSON OBJECT "object?",
  js IS JSON ARRAY "array?"
FROM (VALUES
      ('123'), ('"abc"'), ('{"a": "b"}'), ('[1,2]'),('abc')) foo(js);
     js     | json? | scalar? | object? | array?
------------+-------+---------+---------+--------
 123        | t     | t       | f       | f
 "abc"      | t     | t       | f       | f
 {"a": "b"} | t     | f       | t       | f
 [1,2]      | t     | f       | f       | t
 abc        | f     | f       | f       | f

SELECT js,
  js IS JSON OBJECT "object?",
  js IS JSON ARRAY "array?",
  js IS JSON ARRAY WITH UNIQUE KEYS "array w. UK?",
  js IS JSON ARRAY WITHOUT UNIQUE KEYS "array w/o UK?"
FROM (VALUES ('[{"a":"1"},
 {"b":"2","b":"3"}]')) foo(js);
-[ RECORD 1 ]-+--------------------
js            | [{"a":"1"},        +
              |  {"b":"2","b":"3"}]
object?       | f
array?        | t
array w. UK?  | f
array w/o UK? | t


<xref linkend="functions-json-processing-table"/> shows the functions that are available for processing <type>json</type> and <type>jsonb</type> values. 表 9.49jsonjsonb値を処理するのに使える関数を示します。

表9.49 JSON処理関数

<title>JSON Processing Functions</title>

Function 関数

Description 説明

Example(s)

json_array_elements ( json ) → setof json

jsonb_array_elements ( jsonb ) → setof jsonb

Expands the top-level JSON array into a set of JSON values. トップレベルのJSON配列をJSON値の集合に展開します。

select * from json_array_elements('[1,true, [2,false]]')

   value
-----------
 1
 true
 [2,false]

json_array_elements_text ( json ) → setof text

jsonb_array_elements_text ( jsonb ) → setof text

Expands the top-level JSON array into a set of <type>text</type> values. トップレベルのJSON配列をtext値の集合に展開します。

select * from json_array_elements_text('["foo", "bar"]')

   value
-----------
 foo
 bar

json_array_length ( json ) → integer

jsonb_array_length ( jsonb ) → integer

Returns the number of elements in the top-level JSON array. トップレベルのJSON配列の要素数を返します。

json_array_length('[1,2,3,{"f1":1,"f2":[5,6]},4]')5

jsonb_array_length('[]')0

json_each ( json ) → setof record ( key text, value json )

jsonb_each ( jsonb ) → setof record ( key text, value jsonb )

Expands the top-level JSON object into a set of key/value pairs. トップレベルのJSONオブジェクトをキー/値のペアの集合に展開します。

select * from json_each('{"a":"foo", "b":"bar"}')

 key | value
-----+-------
 a   | "foo"
 b   | "bar"

json_each_text ( json ) → setof record ( key text, value text )

jsonb_each_text ( jsonb ) → setof record ( key text, value text )

Expands the top-level JSON object into a set of key/value pairs. The returned <parameter>value</parameter>s will be of type <type>text</type>. トップレベルのJSONオブジェクトをキー/値のペアの集合に展開します。 返り値のvaluetext型です。

select * from json_each_text('{"a":"foo", "b":"bar"}')

 key | value
-----+-------
 a   | foo
 b   | bar

json_extract_path ( from_json json, VARIADIC path_elems text[] ) → json

jsonb_extract_path ( from_json jsonb, VARIADIC path_elems text[] ) → jsonb

Extracts JSON sub-object at the specified path. (This is functionally equivalent to the <literal>#&gt;</literal> operator, but writing the path out as a variadic list can be more convenient in some cases.) 指定したパスにおけるJSONの副オブジェクトを取り出します。 (これは#>演算子と機能的に同じですが、パスをvariadicリストで書き出す方がより便利な場合があります。)

json_extract_path('{"f2":{"f3":1},"f4":{"f5":99,"f6":"foo"}}', 'f4', 'f6')"foo"

json_extract_path_text ( from_json json, VARIADIC path_elems text[] ) → text

jsonb_extract_path_text ( from_json jsonb, VARIADIC path_elems text[] ) → text

Extracts JSON sub-object at the specified path as <type>text</type>. (This is functionally equivalent to the <literal>#&gt;&gt;</literal> operator.) 指定したパスにおけるJSONの副オブジェクトをtextとして取り出します。 (これは機能的には#>>演算子と同じです。)

json_extract_path_text('{"f2":{"f3":1},"f4":{"f5":99,"f6":"foo"}}', 'f4', 'f6')foo

json_object_keys ( json ) → setof text

jsonb_object_keys ( jsonb ) → setof text

Returns the set of keys in the top-level JSON object. トップレベルのJSONオブジェクト中のキーの集合を返します。

select * from json_object_keys('{"f1":"abc","f2":{"f3":"a", "f4":"b"}}')

 json_object_keys
------------------
 f1
 f2

json_populate_record ( base anyelement, from_json json ) → anyelement

jsonb_populate_record ( base anyelement, from_json jsonb ) → anyelement

Expands the top-level JSON object to a row having the composite type of the <parameter>base</parameter> argument. The JSON object is scanned for fields whose names match column names of the output row type, and their values are inserted into those columns of the output. (Fields that do not correspond to any output column name are ignored.) In typical use, the value of <parameter>base</parameter> is just <literal>NULL</literal>, which means that any output columns that do not match any object field will be filled with nulls. However, if <parameter>base</parameter> isn't <literal>NULL</literal> then the values it contains will be used for unmatched columns. トップレベルのJSONオブジェクトをbase引数である複合型を持つ行に展開します。 JSONオブジェクトは出力行型の列名と一致するフィールドが検査されます。 (出力列名と関連のないフィールドは無視されます。) 典型的な使い方としては、baseの値が単にNULLで、これはオブジェクトフィールドと一致しない出力列にはNULLがセットされることを意味します。 しかし、baseNULLでないなら、それが持つ値が一致しない列に使われます。

To convert a JSON value to the SQL type of an output column, the following rules are applied in sequence: JSON値を出力列のSQL型に変換する際に以下のルールが順に適用されます。

  • A JSON null value is converted to an SQL null in all cases. すべての場合にJSONのNULL値はSQLのNULLに変換されます。

  • If the output column is of type <type>json</type> or <type>jsonb</type>, the JSON value is just reproduced exactly. 出力列がjson型あるいはjsonb型なら、JSON値は単にそのまま複製されます。

  • If the output column is a composite (row) type, and the JSON value is a JSON object, the fields of the object are converted to columns of the output row type by recursive application of these rules. 出力行が複合(行)型でJSON値がJSONオブジェクトなら、これらのルールを再帰的に適用することによって、オブジェクトのフィールドが出力行型の列に変換されます。

  • Likewise, if the output column is an array type and the JSON value is a JSON array, the elements of the JSON array are converted to elements of the output array by recursive application of these rules. 同様に、出力行が配列型でJSON値がJSON配列なら、これらのルールを再帰的に適用することによって、JSON配列の要素が出力配列の要素に変換されます。

  • Otherwise, if the JSON value is a string, the contents of the string are fed to the input conversion function for the column's data type. それ以外の場合で、JSON値が文字列なら、その文字列の内容が列のデータ型に対応する入力変換関数に送られます。

  • Otherwise, the ordinary text representation of the JSON value is fed to the input conversion function for the column's data type. さもなければ、通常のJSON値のテキスト表現が列のデータ型に対応する入力変換関数に送られます。

While the example below uses a constant JSON value, typical use would be to reference a <type>json</type> or <type>jsonb</type> column laterally from another table in the query's <literal>FROM</literal> clause. Writing <function>json_populate_record</function> in the <literal>FROM</literal> clause is good practice, since all of the extracted columns are available for use without duplicate function calls. これらの関数の例ではJSON定数を使用していますが、典型的な使用法はそのjsonまたはjsonb列をFROM句の別のテーブルから外側に参照することです。 FROM句でjson_populate_recordを書くのは良い練習になります。 すべての取り出された列を重複した関数呼び出しなしに利用できるからです。

create type subrowtype as (d int, e text); create type myrowtype as (a int, b text[], c subrowtype);

select * from json_populate_record(null::myrowtype, '{"a": 1, "b": ["2", "a b"], "c": {"d": 4, "e": "a b c"}, "x": "foo"}')

 a |   b       |      c
---+-----------+-------------
 1 | {2,"a b"} | (4,"a b c")

json_populate_recordset ( base anyelement, from_json json ) → setof anyelement

jsonb_populate_recordset ( base anyelement, from_json jsonb ) → setof anyelement

Expands the top-level JSON array of objects to a set of rows having the composite type of the <parameter>base</parameter> argument. Each element of the JSON array is processed as described above for <function>json[b]_populate_record</function>. トップレベルのJSONオブジェクトをbase引数である複合型を持つ行の集合に展開します。 JSON配列の個々の要素は上のjson[b]_populate_recordで説明したように処理されます。

create type twoints as (a int, b int);

select * from json_populate_recordset(null::twoints, '[{"a":1,"b":2}, {"a":3,"b":4}]')

 a | b
---+---
 1 | 2
 3 | 4

json_to_record ( json ) → record

jsonb_to_record ( jsonb ) → record

Expands the top-level JSON object to a row having the composite type defined by an <literal>AS</literal> clause. (As with all functions returning <type>record</type>, the calling query must explicitly define the structure of the record with an <literal>AS</literal> clause.) The output record is filled from fields of the JSON object, in the same way as described above for <function>json[b]_populate_record</function>. Since there is no input record value, unmatched columns are always filled with nulls. トップレベルのJSONオブジェクトをAS句で定義した複合型を持つ行に展開します。 (recordを返すすべての関数では、呼び出す問い合わせは明示的にAS句でレコードの構造を定義しなければなりません。) 上のjson[b]_populate_recordで説明した方法で、出力レコードはJSONオブジェクトのフィールドで満たされます。 入力レコード値がないので、一致しない列は常にNULLで満たされます。

create type myrowtype as (a int, b text);

select * from json_to_record('{"a":1,"b":[1,2,3],"c":[1,2,3],"e":"bar","r": {"a": 123, "b": "a b c"}}') as x(a int, b text, c int[], d text, r myrowtype)

 a |    b    |    c    | d |       r
---+---------+---------+---+---------------
 1 | [1,2,3] | {1,2,3} |   | (123,"a b c")

json_to_recordset ( json ) → setof record

jsonb_to_recordset ( jsonb ) → setof record

Expands the top-level JSON array of objects to a set of rows having the composite type defined by an <literal>AS</literal> clause. (As with all functions returning <type>record</type>, the calling query must explicitly define the structure of the record with an <literal>AS</literal> clause.) Each element of the JSON array is processed as described above for <function>json[b]_populate_record</function>. トップレベルのJSON配列をAS句で定義した複合型を持つ行に展開します。 (recordを返すすべての関数では、呼び出す問い合わせは明示的にAS句でレコードの構造を定義しなければなりません。) 上のjson[b]_populate_recordで説明した方法で、JSON配列の要素は処理されます。

select * from json_to_recordset('[{"a":1,"b":"foo"}, {"a":"2","c":"bar"}]') as x(a int, b text)

 a |  b
---+-----
 1 | foo
 2 |

jsonb_set ( target jsonb, path text[], new_value jsonb [, create_if_missing boolean ] ) → jsonb

Returns <parameter>target</parameter> with the item designated by <parameter>path</parameter> replaced by <parameter>new_value</parameter>, or with <parameter>new_value</parameter> added if <parameter>create_if_missing</parameter> is true (which is the default) and the item designated by <parameter>path</parameter> does not exist. All earlier steps in the path must exist, or the <parameter>target</parameter> is returned unchanged. As with the path oriented operators, negative integers that appear in the <parameter>path</parameter> count from the end of JSON arrays. If the last path step is an array index that is out of range, and <parameter>create_if_missing</parameter> is true, the new value is added at the beginning of the array if the index is negative, or at the end of the array if it is positive. pathで指定された要素をnew_valueで置き換えてtargetを返します。 create_if_missingが真なら(デフォルトです)、pathで指定された項目が無い時にnew_valueが追加されます。 パス中のすべての初期のステップは存在しなければならず、さもなければtargetは変わらないままに返却されます。 パスの位置についての演算子については、pathの中にある負の整数はJSON配列の終わりから数えます。 パスの最後のステップが範囲外の配列のインデックスで、create_if_missingが真のときは、インデックスが負なら配列の最初に、正なら配列の最後に新しい値が追加されます。

jsonb_set('[{"f1":1,"f2":null},2,null,3]', '{0,f1}', '[2,3,4]', false)[{"f1": [2, 3, 4], "f2": null}, 2, null, 3]

jsonb_set('[{"f1":1,"f2":null},2]', '{0,f3}', '[2,3,4]')[{"f1": 1, "f2": null, "f3": [2, 3, 4]}, 2]

jsonb_set_lax ( target jsonb, path text[], new_value jsonb [, create_if_missing boolean [, null_value_treatment text ]] ) → jsonb

If <parameter>new_value</parameter> is not <literal>NULL</literal>, behaves identically to <literal>jsonb_set</literal>. Otherwise behaves according to the value of <parameter>null_value_treatment</parameter> which must be one of <literal>'raise_exception'</literal>, <literal>'use_json_null'</literal>, <literal>'delete_key'</literal>, or <literal>'return_target'</literal>. The default is <literal>'use_json_null'</literal>. new_valueNULLでないなら、jsonb_setと同じ振る舞いをします。 そうでなければnull_value_treatmentにしたがいます。 null_value_treatmentは、'raise_exception''use_json_null''delete_key''return_target'のいずれかでなければなりません。 デフォルトは'use_json_null'です。

jsonb_set_lax('[{"f1":1,"f2":null},2,null,3]', '{0,f1}', null)[{"f1": null, "f2": null}, 2, null, 3]

jsonb_set_lax('[{"f1":99,"f2":null},2]', '{0,f3}', null, true, 'return_target')[{"f1": 99, "f2": null}, 2]

jsonb_insert ( target jsonb, path text[], new_value jsonb [, insert_after boolean ] ) → jsonb

Returns <parameter>target</parameter> with <parameter>new_value</parameter> inserted. If the item designated by the <parameter>path</parameter> is an array element, <parameter>new_value</parameter> will be inserted before that item if <parameter>insert_after</parameter> is false (which is the default), or after it if <parameter>insert_after</parameter> is true. If the item designated by the <parameter>path</parameter> is an object field, <parameter>new_value</parameter> will be inserted only if the object does not already contain that key. All earlier steps in the path must exist, or the <parameter>target</parameter> is returned unchanged. As with the path oriented operators, negative integers that appear in the <parameter>path</parameter> count from the end of JSON arrays. If the last path step is an array index that is out of range, the new value is added at the beginning of the array if the index is negative, or at the end of the array if it is positive. new_valueを挿入してtargetを返します。 pathで指定した項目が配列要素で、insert_afterが偽(デフォルトです)ならばnew_valueはその項目の前に挿入され、insert_afterが真であれば後に挿入されます。 pathで指定した項目がオブジェクトフィールドならば、オブジェクトがすでにそのキーを含んでいない場合にのみnew_valueが挿入されます。 パス中のすべての初期のステップは存在しなければならず、さもなければtargetは変わらないままに返却されます。 pathについての演算子について言うと、path内の負の整数はJSON配列の終わりから数えます。 パスの最後のステップが範囲外の配列のインデックスで、インデックスが負なら配列の最初に、正なら配列の最後に新しい値が追加されます。

jsonb_insert('{"a": [0,1,2]}', '{a, 1}', '"new_value"'){"a": [0, "new_value", 1, 2]}

jsonb_insert('{"a": [0,1,2]}', '{a, 1}', '"new_value"', true){"a": [0, 1, "new_value", 2]}

json_strip_nulls ( json ) → json

jsonb_strip_nulls ( jsonb ) → jsonb

Deletes all object fields that have null values from the given JSON value, recursively. Null values that are not object fields are untouched. 与えられたJSON値からNULLを持つオブジェクトフィールドをすべて削除します。 オブジェクトフィールドではないNULL値は変わりません。

json_strip_nulls('[{"f1":1, "f2":null}, 2, null, 3]')[{"f1":1},2,null,3]

jsonb_path_exists ( target jsonb, path jsonpath [, vars jsonb [, silent boolean ]] ) → boolean

Checks whether the JSON path returns any item for the specified JSON value. If the <parameter>vars</parameter> argument is specified, it must be a JSON object, and its fields provide named values to be substituted into the <type>jsonpath</type> expression. If the <parameter>silent</parameter> argument is specified and is <literal>true</literal>, the function suppresses the same errors as the <literal>@?</literal> and <literal>@@</literal> operators do. JSONパスが指定したJSON値に対して項目を返すかどうかをチェックします。 varsが指定されるなら、それはJSONオブジェクトでなければならず、そのフィールドはjsonpath式に置き換えられる名前を持つ値を提供します。 silent引数が指定されていてtrueなら、この関数は@?@@演算子が生成するのと同じエラーを抑止します。

jsonb_path_exists('{"a":[1,2,3,4,5]}', '$.a[*] ? (@ >= $min && @ <= $max)', '{"min":2, "max":4}')t

jsonb_path_match ( target jsonb, path jsonpath [, vars jsonb [, silent boolean ]] ) → boolean

Returns the result of a JSON path predicate check for the specified JSON value. Only the first item of the result is taken into account. If the result is not Boolean, then <literal>NULL</literal> is returned. The optional <parameter>vars</parameter> and <parameter>silent</parameter> arguments act the same as for <function>jsonb_path_exists</function>. 指定したJSON値のJSONパス述語チェックの結果を返します。 結果の最初の項目だけが考慮されます。 結果がBooleanでないなら、nullが返ります。 オプションのvarssilent引数はjsonb_path_existsと同じように働きます。

jsonb_path_match('{"a":[1,2,3,4,5]}', 'exists($.a[*] ? (@ >= $min && @ <= $max))', '{"min":2, "max":4}')t

jsonb_path_query ( target jsonb, path jsonpath [, vars jsonb [, silent boolean ]] ) → setof jsonb

Returns all JSON items returned by the JSON path for the specified JSON value. The optional <parameter>vars</parameter> and <parameter>silent</parameter> arguments act the same as for <function>jsonb_path_exists</function>. JSON値に対するJSONパスによって返されるすべてのJSON項目を返します。 オプションのvarssilent引数はjsonb_path_existsと同じように働きます。

select * from jsonb_path_query('{"a":[1,2,3,4,5]}', '$.a[*] ? (@ >= $min && @ <= $max)', '{"min":2, "max":4}')

 jsonb_path_query
------------------
 2
 3
 4

jsonb_path_query_array ( target jsonb, path jsonpath [, vars jsonb [, silent boolean ]] ) → jsonb

Returns all JSON items returned by the JSON path for the specified JSON value, as a JSON array. The optional <parameter>vars</parameter> and <parameter>silent</parameter> arguments act the same as for <function>jsonb_path_exists</function>. JSON値に対するJSONパスによって返されるすべてのJSON項目をJSON配列として返します。 オプションのvarssilent引数はjsonb_path_existsと同じように働きます。

jsonb_path_query_array('{"a":[1,2,3,4,5]}', '$.a[*] ? (@ >= $min && @ <= $max)', '{"min":2, "max":4}')[2, 3, 4]

jsonb_path_query_first ( target jsonb, path jsonpath [, vars jsonb [, silent boolean ]] ) → jsonb

Returns the first JSON item returned by the JSON path for the specified JSON value. Returns <literal>NULL</literal> if there are no results. The optional <parameter>vars</parameter> and <parameter>silent</parameter> arguments act the same as for <function>jsonb_path_exists</function>. JSON値に対するJSONパスによって返される最初のJSON項目を返します。 結果がなければNULLが返ります。 オプションのvarssilent引数はjsonb_path_existsと同じように働きます。

jsonb_path_query_first('{"a":[1,2,3,4,5]}', '$.a[*] ? (@ >= $min && @ <= $max)', '{"min":2, "max":4}')2

jsonb_path_exists_tz ( target jsonb, path jsonpath [, vars jsonb [, silent boolean ]] ) → boolean

jsonb_path_match_tz ( target jsonb, path jsonpath [, vars jsonb [, silent boolean ]] ) → boolean

jsonb_path_query_tz ( target jsonb, path jsonpath [, vars jsonb [, silent boolean ]] ) → setof jsonb

jsonb_path_query_array_tz ( target jsonb, path jsonpath [, vars jsonb [, silent boolean ]] ) → jsonb

jsonb_path_query_first_tz ( target jsonb, path jsonpath [, vars jsonb [, silent boolean ]] ) → jsonb

These functions act like their counterparts described above without the <literal>_tz</literal> suffix, except that these functions support comparisons of date/time values that require timezone-aware conversions. The example below requires interpretation of the date-only value <literal>2015-08-02</literal> as a timestamp with time zone, so the result depends on the current <xref linkend="guc-timezone"/> setting. Due to this dependency, these functions are marked as stable, which means these functions cannot be used in indexes. Their counterparts are immutable, and so can be used in indexes; but they will throw errors if asked to make such comparisons. これらの関数は、時間帯を考慮する日時値の比較をサポートすることを除いて、上で述べた、_tz接尾を除いた片割れの関数のように動作します。 以下の例では日付のみの値2015-08-02を時間帯付きタイムスタンプとして解釈することが必要で、結果はTimeZone設定に依存します。 この依存性のために、これらの関数は安定(stable)、として印付けされており、インデックスにはこれらの関数は使えないことを意味します。 これらの関数の片割れは不変(immutable)なので、インデックスで使えます。しかし、そうした比較を要求されるとエラーを吐きます。

jsonb_path_exists_tz('["2015-08-01 12:00:00-05"]', '$[*] ? (@.datetime() < "2015-08-02".datetime())')t

jsonb_pretty ( jsonb ) → text

Converts the given JSON value to pretty-printed, indented text. 与えられたJSON値を整形されたインデント付きテキストに変換します。

jsonb_pretty('[{"f1":1,"f2":null}, 2]')

[
    {
        "f1": 1,
        "f2": null
    },
    2
]

json_typeof ( json ) → text

jsonb_typeof ( jsonb ) → text

Returns the type of the top-level JSON value as a text string. Possible types are <literal>object</literal>, <literal>array</literal>, <literal>string</literal>, <literal>number</literal>, <literal>boolean</literal>, and <literal>null</literal>. (The <literal>null</literal> result should not be confused with an SQL NULL; see the examples.) トップレベルのJSON値の型をテキスト文字列として返します。 可能な型は次のとおりです。 objectarraystringnumberbooleannull。 (nullの結果をSQLのNULLと混同してはいけません。以下の例をご覧ください。)

json_typeof('-123.4')number

json_typeof('null'::json)null

json_typeof(NULL::json) IS NULLt


9.16.2. SQL/JSONパス言語 #

<title>The SQL/JSON Path Language</title>

SQL/JSON path expressions specify the items to be retrieved from the JSON data, similar to XPath expressions used for SQL access to XML. In <productname>PostgreSQL</productname>, path expressions are implemented as the <type>jsonpath</type> data type and can use any elements described in <xref linkend="datatype-jsonpath"/>. SQL/JSONパス式は、XMLへのSQLアクセスで使用されるXPath同様、JSONデータから取り出す項目を指定します。 PostgreSQLではパス式はjsonpathデータ型として実装されており、8.14.7で説明されているすべての要素を使うことができます。

JSON query functions and operators pass the provided path expression to the <firstterm>path engine</firstterm> for evaluation. If the expression matches the queried JSON data, the corresponding JSON item, or set of items, is returned. Path expressions are written in the SQL/JSON path language and can include arithmetic expressions and functions. JSON問い合わせ関数と演算子は与えられたパス式をpath engineに渡して評価します。 式が問い合わせ対象のJSONデータにマッチすれば、関連するSQL/JSON項目が返却されます。 パス式はSQL/JSONパス言語で書かれ、算術式と関数を含むことができます。

A path expression consists of a sequence of elements allowed by the <type>jsonpath</type> data type. The path expression is normally evaluated from left to right, but you can use parentheses to change the order of operations. If the evaluation is successful, a sequence of JSON items is produced, and the evaluation result is returned to the JSON query function that completes the specified computation. パス式はjsonpathデータ型で認められた一連の要素からなります。 パス式は通常左から右へと評価されますが、括弧を使って演算の順序を変更することができます。 評価が成功すれば、一連のJSON項目が生成され、評価結果が指定した計算を完了したJSON問い合わせ関数に戻されます。

To refer to the JSON value being queried (the <firstterm>context item</firstterm>), use the <literal>$</literal> variable in the path expression. It can be followed by one or more <link linkend="type-jsonpath-accessors">accessor operators</link>, which go down the JSON structure level by level to retrieve sub-items of the context item. Each operator that follows deals with the result of the previous evaluation step. 問い合わせ対象(context item)のJSONデータを参照するには、パス式内で$値を使います。 複数のアクセサ演算子をその後に記述することもできます。 それによってJSON構造をレベル順に訪れて文脈項目の副項目の内容を取り出します。 後続の個々の演算子はその前の評価段階の結果を処理します。

For example, suppose you have some JSON data from a GPS tracker that you would like to parse, such as: たとえば、次のようなパースしたいGPSトラッカーからのJSONデータがあるとします。

{
  "track": {
    "segments": [
      {
        "location":   [ 47.763, 13.4034 ],
        "start time": "2018-10-14 10:05:14",
        "HR": 73
      },
      {
        "location":   [ 47.706, 13.2635 ],
        "start time": "2018-10-14 10:39:21",
        "HR": 135
      }
    ]
  }
}

To retrieve the available track segments, you need to use the <literal>.<replaceable>key</replaceable></literal> accessor operator to descend through surrounding JSON objects: 存在するトラックセグメントを取り出すには、.keyアクセサ演算子を使用して、周辺のJSONオブジェクトを下っていく必要があります。

$.track.segments

To retrieve the contents of an array, you typically use the <literal>[*]</literal> operator. For example, the following path will return the location coordinates for all the available track segments: 配列の内容を取り出すには、典型的には[*]演算子を使います。 たとえば次のパスはすべての存在するトラックセグメントの位置座標を返します。

$.track.segments[*].location

To return the coordinates of the first segment only, you can specify the corresponding subscript in the <literal>[]</literal> accessor operator. Recall that JSON array indexes are 0-relative: 最初のセグメントの座標だけを返すには、[]アクセサ演算子の中で対応する添え字を指定することができます。 JSON配列インデックスは0スタートであることに注意してください。

$.track.segments[0].location

The result of each path evaluation step can be processed by one or more <type>jsonpath</type> operators and methods listed in <xref linkend="functions-sqljson-path-operators"/>. Each method name must be preceded by a dot. For example, you can get the size of an array: 各段階でのパス評価結果は9.16.2.2に列挙されている一つ以上のjsonpath演算子とメソッドで処理することができます。 各々のメソッド名の前にピリオドを付けなければなりません。 たとえば配列の大きさを得ることができます。

$.track.segments.size()

More examples of using <type>jsonpath</type> operators and methods within path expressions appear below in <xref linkend="functions-sqljson-path-operators"/>. パス式内のjsonpath演算子とメソッドを使用する他の例については以下の9.16.2.2を参照してください。

When defining a path, you can also use one or more <firstterm>filter expressions</firstterm> that work similarly to the <literal>WHERE</literal> clause in SQL. A filter expression begins with a question mark and provides a condition in parentheses: パスを定義する際にはSQLのWHERE節のように働く一つ以上のフィルター式が利用できます。 フィルター式はクェスチョンマークで始まり、カッコ内に条件を記述します。

? (condition)

Filter expressions must be written just after the path evaluation step to which they should apply. The result of that step is filtered to include only those items that satisfy the provided condition. SQL/JSON defines three-valued logic, so the condition can be <literal>true</literal>, <literal>false</literal>, or <literal>unknown</literal>. The <literal>unknown</literal> value plays the same role as SQL <literal>NULL</literal> and can be tested for with the <literal>is unknown</literal> predicate. Further path evaluation steps use only those items for which the filter expression returned <literal>true</literal>. フィルター式はそれを適用するパス評価段階の直後に指定しなければなりません。 この段階の結果は、指定した条件を満たす項目だけが含まれるようにフィルターされます。 SQL/JSONは3値論理を定義しており、条件はtruefalseunknownのどれかです。 unknownは値はSQLのNULLと同じ役割を果たし、is unknown述語で評価できます。 その後の評価段階ではtrueを返すフィルター式に対応する項目だけが使われます。

The functions and operators that can be used in filter expressions are listed in <xref linkend="functions-sqljson-filter-ex-table"/>. Within a filter expression, the <literal>@</literal> variable denotes the value being filtered (i.e., one result of the preceding path step). You can write accessor operators after <literal>@</literal> to retrieve component items. フィルター式内で利用できる関数と演算子は表 9.51にリストされています。 フィルター式内では、フィルターする必要のある値は@変数で示します。(つまり以前のパスステップの結果の一つです。) コンポーネント項目を取得するためにアクセサ演算子を@の後に記述することができます。

For example, suppose you would like to retrieve all heart rate values higher than 130. You can achieve this using the following expression: たとえば130より高いすべての心拍数を取り出したいとします。次の式を使ってそれを得ることができます。

$.track.segments[*].HR ? (@ > 130)

To get the start times of segments with such values, you have to filter out irrelevant segments before returning the start times, so the filter expression is applied to the previous step, and the path used in the condition is different: そうした値を持つセグメントの開始時刻を得たい場合は、開始時刻を返す前に無関係のセグメントを取り除く必要があります。 そうすることにより前の段階にフィルター式が適用されるので、その条件で適用されるパスは異なります。

$.track.segments[*] ? (@.HR > 130)."start time"

You can use several filter expressions in sequence, if required. For example, the following expression selects start times of all segments that contain locations with relevant coordinates and high heart rate values: 必要なら複数のフィルター式を順に使用することができます。 たとえば次の式は指定した座標と高い心拍数値を持つ位置を持つすべてのセグメントを選択します。

$.track.segments[*] ? (@.location[1] < 13.4) ? (@.HR > 130)."start time"

Using filter expressions at different nesting levels is also allowed. The following example first filters all segments by location, and then returns high heart rate values for these segments, if available: 異なる入れ子レベルに対してフィルター式を適用することもできます。 次の例では、まず位置ですべてのセグメントをフィルターし、もしあれば高い心拍数値を返します。

$.track.segments[*] ? (@.location[1] < 13.4).HR ? (@ > 130)

You can also nest filter expressions within each other: フィルター式をお互いに入れ子にすることもできます。

$.track ? (exists(@.segments[*] ? (@.HR > 130))).segments.size()

This expression returns the size of the track if it contains any segments with high heart rate values, or an empty sequence otherwise. この式は高い心拍数値を含むトラックがあればそのすべてのサイズを返します。もしなければ空のシーケンスが返ります。

<productname>PostgreSQL</productname>'s implementation of the SQL/JSON path language has the following deviations from the SQL/JSON standard: PostgreSQLのSQL/JSONパス言語の実装はSQL/JSON標準と次の点が異なります。

  • A path expression can be a Boolean predicate, although the SQL/JSON standard allows predicates only in filters. This is necessary for implementation of the <literal>@@</literal> operator. For example, the following <type>jsonpath</type> expression is valid in <productname>PostgreSQL</productname>: SQL/JSON標準ではフィルター内でのみ述語が使えますが、パス式はBoolean述語でも構いません。 これは@@演算子を実装するために必要です。 たとえば、次のjsonpath式はPostgreSQLでは有効です。

    $.track.segments[*].HR < 70
    

  • There are minor differences in the interpretation of regular expression patterns used in <literal>like_regex</literal> filters, as described in <xref linkend="jsonpath-regular-expressions"/>. 9.16.2.3で述べるように、like_regexフィルターで使用される正規表現パターンの解釈には些細な違いがあります。

9.16.2.1. 厳密モードと非厳密モード #

<title>Strict and Lax Modes</title>

When you query JSON data, the path expression may not match the actual JSON data structure. An attempt to access a non-existent member of an object or element of an array results in a structural error. SQL/JSON path expressions have two modes of handling structural errors: JSONデータを問い合わせる際、パス式は実際のJSONデータ構造に一致しないかも知れません。 存在しないオブジェクトのメンバーあるいは配列要素にアクセスしようとすると、構造上のエラーとなります。 SQL/JSONパス式には構造上のエラーを扱うための2つのモードがあります。

  • lax (default) &mdash; the path engine implicitly adapts the queried data to the specified path. Any remaining structural errors are suppressed and converted to empty SQL/JSON sequences. 非厳密(lax)モード(デフォルト)— パスエンジンは指定したパスを問い合わせデータに暗黙的に適合させます。 構造上のエラーは抑止され、空のSQL/JSONシーケンスへと変換されます。

  • strict &mdash; if a structural error occurs, an error is raised. 厳密(strict)モード — 構造上のエラーがあるとエラーが発生します。

The lax mode facilitates matching of a JSON document structure and path expression if the JSON data does not conform to the expected schema. If an operand does not match the requirements of a particular operation, it can be automatically wrapped as an SQL/JSON array or unwrapped by converting its elements into an SQL/JSON sequence before performing this operation. Besides, comparison operators automatically unwrap their operands in the lax mode, so you can compare SQL/JSON arrays out-of-the-box. An array of size 1 is considered equal to its sole element. Automatic unwrapping is not performed only when: 非厳密モードは、JSONデータが期待されるスキーマに沿わないときにJSON文書構造とパス式のマッチングを助けます。 あるオペランドが操作の要件に合わないときにはそれをSQL/JSON配列にまとめたり、あるいは操作を行う前にそれをSQL/JSONシーケンスに展開することもできます。 また非厳密モードにおいては、比較演算子は自動的にオペランドを展開し、SQL/JSON配列をそのまま比較することができます。 大きさ1の配列はその単独要素と同じものとして扱われます。 自動展開は以下の場合にのみ行われません。

  • The path expression contains <literal>type()</literal> or <literal>size()</literal> methods that return the type and the number of elements in the array, respectively. それぞれ配列の型、要素数を返すtype()size()をパス式が含む。

  • The queried JSON data contain nested arrays. In this case, only the outermost array is unwrapped, while all the inner arrays remain unchanged. Thus, implicit unwrapping can only go one level down within each path evaluation step. 問い合わせ対象のJSONデータが入れ子の配列を含む。 この場合はもっとも外側の配列のみが展開され、内側の配列は変わりません。 ですから、それぞれの評価段階において1レベルのみに暗黙的な展開が行われます。

For example, when querying the GPS data listed above, you can abstract from the fact that it stores an array of segments when using the lax mode: たとえば、上述のGPSデータに問い合わせする際、非厳密モードでは配列のセグメントを含んでいることを抽象化できます。

lax $.track.segments.location

In the strict mode, the specified path must exactly match the structure of the queried JSON document to return an SQL/JSON item, so using this path expression will cause an error. To get the same result as in the lax mode, you have to explicitly unwrap the <literal>segments</literal> array: 厳密モードでは、指定したパスはSQL/JSON項目を返す問い合わせ対象のJSON文書の構造に正確に一致していなければなりません。ですから、このパス式を使うとエラーになります。 非厳密モードと同じ結果を得るためには、segments配列を明示的に展開する必要があります。

strict $.track.segments[*].location

The <literal>.**</literal> accessor can lead to surprising results when using the lax mode. For instance, the following query selects every <literal>HR</literal> value twice: .**アクセサを非厳密モードで使うと驚くべき結果をもたらすことがあります。 たとえば、次の問い合わせはすべてのHR値を2回検索します。

lax $.**.HR

This happens because the <literal>.**</literal> accessor selects both the <literal>segments</literal> array and each of its elements, while the <literal>.HR</literal> accessor automatically unwraps arrays when using the lax mode. To avoid surprising results, we recommend using the <literal>.**</literal> accessor only in the strict mode. The following query selects each <literal>HR</literal> value just once: これは.**アクセサがsegmentsとその各々の要素の両方を検索するからです。 一方、.HRアクセサは非厳密モードでは自動的に配列を展開します。 予期しない結果を避けるには、.**アクセサを厳密モードでのみ使うことをお勧めします。 次の問い合わせはHRの各値を一度だけ検索します。

strict $.**.HR

9.16.2.2. SQL/JSONパス演算子とメソッド #

<title>SQL/JSON Path Operators and Methods</title>

<xref linkend="functions-sqljson-op-table"/> shows the operators and methods available in <type>jsonpath</type>. Note that while the unary operators and methods can be applied to multiple values resulting from a preceding path step, the binary operators (addition etc.) can only be applied to single values. 表 9.50jsonpathで利用可能な演算子とメソッドを示します。 単項演算子とメソッドは以前のパスステップから生じた複数の値に適用できますが、二項演算子(加算など)は単一の値にしか適用できないことに注意してください。

表9.50 jsonpath演算子とメソッド

<title><type>jsonpath</type> Operators and Methods</title>

Operator/Method 演算子/メソッド

Description 説明

Example(s)

number + numbernumber

Addition 加算

jsonb_path_query('[2]', '$[0] + 3')5

+ numbernumber

Unary plus (no operation); unlike addition, this can iterate over multiple values 単項のプラス(演算なし)。加算と違って、複数の値に渡って適用できます。

jsonb_path_query_array('{"x": [2,3,4]}', '+ $.x')[2, 3, 4]

number - numbernumber

Subtraction 減算

jsonb_path_query('[2]', '7 - $[0]')5

- numbernumber

Negation; unlike subtraction, this can iterate over multiple values 負符号。減算と違って、複数の値に渡って適用できます。

jsonb_path_query_array('{"x": [2,3,4]}', '- $.x')[-2, -3, -4]

number * numbernumber

Multiplication 乗算

jsonb_path_query('[4]', '2 * $[0]')8

number / numbernumber

Division 除算

jsonb_path_query('[8.5]', '$[0] / 2')4.2500000000000000

number % numbernumber

Modulo (remainder) 剰余(残り)

jsonb_path_query('[32]', '$[0] % 10')2

value . type()string

Type of the JSON item (see <function>json_typeof</function>) JSON項目の型(json_typeofを参照)

jsonb_path_query_array('[1, "2", {}]', '$[*].type()')["number", "string", "object"]

value . size()number

Size of the JSON item (number of array elements, or 1 if not an array) JSON項目の大きさ(配列の要素数。配列でなければ1)

jsonb_path_query('{"m": [11, 15]}', '$.m.size()')2

value . double()number

Approximate floating-point number converted from a JSON number or string JSON数値あるいは文字列から変換した概算の浮動小数点数

jsonb_path_query('{"len": "1.9"}', '$.len.double() * 2')3.8

number . ceiling()number

Nearest integer greater than or equal to the given number 引数より大きいか等しく、与えられた数に最も近い整数

jsonb_path_query('{"h": 1.3}', '$.h.ceiling()')2

number . floor()number

Nearest integer less than or equal to the given number 引数より小さいか等しく、与えられた数に最も近い整数

jsonb_path_query('{"h": 1.7}', '$.h.floor()')1

number . abs()number

Absolute value of the given number 与えられた数の絶対値

jsonb_path_query('{"z": -0.3}', '$.z.abs()')0.3

string . datetime()datetime_type (see note)

Date/time value converted from a string 文字列から変換した日時値

jsonb_path_query('["2015-8-1", "2015-08-12"]', '$[*] ? (@.datetime() < "2015-08-2".datetime())')"2015-8-1"

string . datetime(template)datetime_type (see note)

Date/time value converted from a string using the specified <function>to_timestamp</function> template 指定のto_timestampテンプレートを使って文字列から変換した日時値

jsonb_path_query_array('["12:30", "18:40"]', '$[*].datetime("HH24:MI")')["12:30:00", "18:40:00"]

object . keyvalue()array

The object's key-value pairs, represented as an array of objects containing three fields: <literal>"key"</literal>, <literal>"value"</literal>, and <literal>"id"</literal>; <literal>"id"</literal> is a unique identifier of the object the key-value pair belongs to 以下の3つのフィールドを含むオブジェクトの配列で表現したオブジェクトのキー/値ペア。 "key""value""id""id"はキー/値ペアが属するオブジェクトのユニーク識別子です。

jsonb_path_query_array('{"x": "20", "y": 32}', '$.keyvalue()')[{"id": 0, "key": "x", "value": "20"}, {"id": 0, "key": "y", "value": 32}]


注記

The result type of the <literal>datetime()</literal> and <literal>datetime(<replaceable>template</replaceable>)</literal> methods can be <type>date</type>, <type>timetz</type>, <type>time</type>, <type>timestamptz</type>, or <type>timestamp</type>. Both methods determine their result type dynamically. datetime()datetime(template)の結果型はdatetimetztimetimestamptz、あるいはtimestampです。 両方のメソッドは結果型を動的に決定します。

The <literal>datetime()</literal> method sequentially tries to match its input string to the ISO formats for <type>date</type>, <type>timetz</type>, <type>time</type>, <type>timestamptz</type>, and <type>timestamp</type>. It stops on the first matching format and emits the corresponding data type. datetime()メソッドは入力文字列をdatetimetztimetimestamptztimestampのISO形式に対して順にマッチを試みます。 最初にマッチした形式で停止し、関連するデータ型を出力します。

The <literal>datetime(<replaceable>template</replaceable>)</literal> method determines the result type according to the fields used in the provided template string. datetime(template)メソッドは与えられたテンプレート文字列にあるフィールドに従って結果型を決定します。

The <literal>datetime()</literal> and <literal>datetime(<replaceable>template</replaceable>)</literal> methods use the same parsing rules as the <literal>to_timestamp</literal> SQL function does (see <xref linkend="functions-formatting"/>), with three exceptions. First, these methods don't allow unmatched template patterns. Second, only the following separators are allowed in the template string: minus sign, period, solidus (slash), comma, apostrophe, semicolon, colon and space. Third, separators in the template string must exactly match the input string. datetime()datetime(template)to_timestampSQL関数と同じ解析ルール(参照9.8)を用いますが、3つの例外があります。 一番目に、これらのメソッドは一致しないテンプレートパターンを許容しません。二番目に次の区切り文字のみを許容します。負符号、ピリオド、斜線(スラッシュ)、カンマ、アポストロフィー、セミコロン、コロン、空白、です。 三番目にテンプレート文字列中の区切り文字は正確に入力文字列と一致しなければなりません。

If different date/time types need to be compared, an implicit cast is applied. A <type>date</type> value can be cast to <type>timestamp</type> or <type>timestamptz</type>, <type>timestamp</type> can be cast to <type>timestamptz</type>, and <type>time</type> to <type>timetz</type>. However, all but the first of these conversions depend on the current <xref linkend="guc-timezone"/> setting, and thus can only be performed within timezone-aware <type>jsonpath</type> functions. 異なる日時型の比較が必要なら、暗黙的なキャストが適用されます。 date値はtimestampあるいはtimestamptzにキャストできます。 timestamptimestamptzに、timetimetzにキャストできます。 しかし、これらの変換の最初のものは現在のTimeZone設定に依存します。ですから時間帯を認識するjsonpath関数中でのみ実行可能です。

<xref linkend="functions-sqljson-filter-ex-table"/> shows the available filter expression elements. 表 9.51に利用可能なフィルター式要素を示します。

表9.51 jsonpathフィルター式要素

<title><type>jsonpath</type> Filter Expression Elements</title>

Predicate/Value 述語/値

Description 説明

Example(s)

value == valueboolean

Equality comparison (this, and the other comparison operators, work on all JSON scalar values) 等値比較(これと他の比較演算子はすべてのJSONスカラー値で使えます)

jsonb_path_query_array('[1, "a", 1, 3]', '$[*] ? (@ == 1)')[1, 1]

jsonb_path_query_array('[1, "a", 1, 3]', '$[*] ? (@ == "a")')["a"]

value != valueboolean

value <> valueboolean

Non-equality comparison 非等値比較

jsonb_path_query_array('[1, 2, 1, 3]', '$[*] ? (@ != 1)')[2, 3]

jsonb_path_query_array('["a", "b", "c"]', '$[*] ? (@ <> "b")')["a", "c"]

value < valueboolean

Less-than comparison 未満比較

jsonb_path_query_array('[1, 2, 3]', '$[*] ? (@ < 2)')[1]

value <= valueboolean

Less-than-or-equal-to comparison 以下比較

jsonb_path_query_array('["a", "b", "c"]', '$[*] ? (@ <= "b")')["a", "b"]

value > valueboolean

Greater-than comparison より大きい比較

jsonb_path_query_array('[1, 2, 3]', '$[*] ? (@ > 2)')[3]

value >= valueboolean

Greater-than-or-equal-to comparison 以上比較

jsonb_path_query_array('[1, 2, 3]', '$[*] ? (@ >= 2)')[2, 3]

trueboolean

JSON constant <literal>true</literal> JSON定数

jsonb_path_query('[{"name": "John", "parent": false}, {"name": "Chris", "parent": true}]', '$[*] ? (@.parent == true)'){"name": "Chris", "parent": true}

falseboolean

JSON constant <literal>false</literal> JSON定数

jsonb_path_query('[{"name": "John", "parent": false}, {"name": "Chris", "parent": true}]', '$[*] ? (@.parent == false)'){"name": "John", "parent": false}

nullvalue

JSON constant <literal>null</literal> (note that, unlike in SQL, comparison to <literal>null</literal> works normally) JSON定数null(SQLとは違ってnullとの比較は通常通り動作することに注意してください。)

jsonb_path_query('[{"name": "Mary", "job": null}, {"name": "Michael", "job": "driver"}]', '$[*] ? (@.job == null) .name')"Mary"

boolean && booleanboolean

Boolean AND 論理AND

jsonb_path_query('[1, 3, 7]', '$[*] ? (@ > 1 && @ < 5)')3

boolean || booleanboolean

Boolean OR 論理OR

jsonb_path_query('[1, 3, 7]', '$[*] ? (@ < 1 || @ > 5)')7

! booleanboolean

Boolean NOT 論理NOT

jsonb_path_query('[1, 3, 7]', '$[*] ? (!(@ < 5))')7

boolean is unknownboolean

Tests whether a Boolean condition is <literal>unknown</literal>. 論理条件がunknownであるかどうかを検査します。

jsonb_path_query('[-1, 2, 7, "foo"]', '$[*] ? ((@ > 0) is unknown)')"foo"

string like_regex string [ flag string ] → boolean

Tests whether the first operand matches the regular expression given by the second operand, optionally with modifications described by a string of <literal>flag</literal> characters (see <xref linkend="jsonpath-regular-expressions"/>). 最初のオペランドが2番目のオペランドで与えられる正規表現にマッチするかどうか検査します。 オプションでflag文字列で記述される変更を伴います。(9.16.2.3を参照してください。)

jsonb_path_query_array('["abc", "abd", "aBdC", "abdacb", "babc"]', '$[*] ? (@ like_regex "^ab.*c")')["abc", "abdacb"]

jsonb_path_query_array('["abc", "abd", "aBdC", "abdacb", "babc"]', '$[*] ? (@ like_regex "^ab.*c" flag "i")')["abc", "aBdC", "abdacb"]

string starts with stringboolean

Tests whether the second operand is an initial substring of the first operand. 2番目の文字列が1番目のオペランドの最初の部分文字列かどうかを検査します。

jsonb_path_query('["John Smith", "Mary Stone", "Bob Johnson"]', '$[*] ? (@ starts with "John")')"John Smith"

exists ( path_expression )boolean

Tests whether a path expression matches at least one SQL/JSON item. Returns <literal>unknown</literal> if the path expression would result in an error; the second example uses this to avoid a no-such-key error in strict mode. パス式が少なくとも一つのSQL/JSON項目とマッチするかどうかを検査します。 パス式がエラーとなる場合はunknownを返します。2番目の例は厳密モードでキーが存在しないエラーを回避するためにこれを使っています。

jsonb_path_query('{"x": [1, 2], "y": [2, 4]}', 'strict $.* ? (exists (@ ? (@[*] > 2)))')[2, 4]

jsonb_path_query_array('{"value": 41}', 'strict $ ? (exists (@.name)) .name')[]


9.16.2.3. SQL/JSON正規表現 #

<title>SQL/JSON Regular Expressions</title>

SQL/JSON path expressions allow matching text to a regular expression with the <literal>like_regex</literal> filter. For example, the following SQL/JSON path query would case-insensitively match all strings in an array that start with an English vowel: SQL/JSONパス式ではlike_regexフィルターを使ってテキストを正規表現にマッチさせることができます。 たとえば、次のSQL/JSONパス式問い合わせは、英語の母音で始まる配列内のすべての文字列に大文字小文字を無視してマッチするでしょう。

$[*] ? (@ like_regex "^[aeiou]" flag "i")

The optional <literal>flag</literal> string may include one or more of the characters <literal>i</literal> for case-insensitive match, <literal>m</literal> to allow <literal>^</literal> and <literal>$</literal> to match at newlines, <literal>s</literal> to allow <literal>.</literal> to match a newline, and <literal>q</literal> to quote the whole pattern (reducing the behavior to a simple substring match). オプションのflag文字列は一つ以上の文字を含むことができます。 iは大文字小文字を無視したマッチ、m^$で改行にマッチ、s.が改行にマッチ、qはパターン全体を参照します。(振る舞いを単純な部分文字列マッチとします)

The SQL/JSON standard borrows its definition for regular expressions from the <literal>LIKE_REGEX</literal> operator, which in turn uses the XQuery standard. PostgreSQL does not currently support the <literal>LIKE_REGEX</literal> operator. Therefore, the <literal>like_regex</literal> filter is implemented using the POSIX regular expression engine described in <xref linkend="functions-posix-regexp"/>. This leads to various minor discrepancies from standard SQL/JSON behavior, which are cataloged in <xref linkend="posix-vs-xquery"/>. Note, however, that the flag-letter incompatibilities described there do not apply to SQL/JSON, as it translates the XQuery flag letters to match what the POSIX engine expects. SQL/JSON標準は正規表現の定義を、XQuery標準を使用するLIKE_REGEX演算子から借りています。 PostgreSQLは今の所LIKE_REGEX演算子をサポートしていません。 ですから、like_regexフィルターは9.7.3で説明されているPOSIX正規表現で実装されています。 このことにより、9.7.3.8で列挙されているSQL/JSON標準の振る舞いとの小さな違いが生じます。 しかし、ここで述べているフラグ文字の非互換性はSQL/JSONには適用されないことに注意してください。SQL/JSONは、XQueryのフラグ文字をPOSIXエンジンが期待するのと一致するように解釈するからです。

Keep in mind that the pattern argument of <literal>like_regex</literal> is a JSON path string literal, written according to the rules given in <xref linkend="datatype-jsonpath"/>. This means in particular that any backslashes you want to use in the regular expression must be doubled. For example, to match string values of the root document that contain only digits: like_regexのパターン引数は8.14.7で説明されているルールにしたがって書かれたJSONパス文字列リテラルであることに注意してください。 これは、正規表現で使用するすべてのバックスラッシュを二重に書かなければならないことを意味します。 たとえば、数字のみを含むroot文書の文字列値にマッチさせるには以下のようにします。

$.* ? (@ like_regex "^\\d+$")