9.15. JSON Functions and Operators

Table 9-40 shows the operators that are available for use with the two JSON datatypes (see Section 8.14).

Table 9-40. json and jsonb Operators

OperatorRight Operand TypeDescriptionExampleExample Result
->intGet JSON array element'[{"a":"foo"},{"a":"bar"},{"a":"baz"}]'::json->2{"a":"baz"}
->textGet JSON object field'{"a": {"b":"foo"}}'::json->'a'{"b":"foo"}
->>intGet JSON array element as text'[1,2,3]'::json->>23
->>textGet JSON object field as text'{"a":1,"b":2}'::json->>'b'2
#>text[]Get JSON object at specified path'{"a": {"b":{"c": "foo"}}}'::json#>'{a,b}'{"c": "foo"}
#>>text[]Get JSON object at specified path as text'{"a":[1,2,3],"b":[4,5,6]}'::json#>>'{a,2}'3

Note: There are parallel variants of these operators for both the json and jsonb types. In addition to those operators common to both types, a further set of operators exists for jsonb (which comprise the default GIN operator class).

The following are jsonb-only operators, used by jsonb operator classes. For a full description of jsonb containment semantics and nesting, see Section 8.14.4. Section 8.14.5 describes how these operators can be used to effectively index jsonb.

Table 9-41. Additonal JSONB Operators

OperatorRight Operand TypeDescriptionExample
=jsonbIs the jsonb equal to this jsonb?'[1,2,3]'::jsonb = '[1,2,3]'::jsonb
@>jsonbDoes the jsonb contain within it this jsonb?'{"a":1, "b":2}'::jsonb @> '{"b":2}'::jsonb
<@jsonbDoes the jsonb have contained within it this jsonb?'{"b":2}'::jsonb <@ '{"a":1, "b":2}'::jsonb
?textDoes this key/element string exist?'{"a":1, "b":2}'::jsonb ? 'b'
?|text[]Do any of these key/element strings exist?'{"a":1, "b":2, "c":3}'::jsonb ?| array['b', 'c']
?&text[]Do all of these key/element strings exist?'["a", "b"]'::jsonb ?& array['a', 'b']

Table 9-42 shows the functions that are available for creating json values. (see Section 8.14)

Table 9-42. JSON Creation Functions

FunctionReturn TypeDescriptionExampleExample Result
array_to_json(anyarray [, pretty_bool]) json Returns the array as JSON. A PostgreSQL multidimensional array becomes a JSON array of arrays. Line feeds will be added between dimension 1 elements if pretty_bool is true. array_to_json('{{1,5},{99,100}}'::int[])[[1,5],[99,100]]
row_to_json(record [, pretty_bool]) json Returns the row as JSON. Line feeds will be added between level 1 elements if pretty_bool is true. row_to_json(row(1,'foo')){"f1":1,"f2":"foo"}
to_json(anyelement) json Returns the value as JSON. If the data type is not built in, and there is a cast from the type to json, the cast function will be used to perform the conversion. Otherwise, for any value other than a number, a Boolean, or a null value, the text representation will be used, escaped and quoted so that it is legal JSON. to_json('Fred said "Hi."'::text)"Fred said \"Hi.\""
json_build_array(VARIADIC "any") json Builds a heterogeneously-typed json array out of a variadic argument list. SELECT json_build_array(1,2,'3',4,5);
 json_build_array
-------------------
 [1, 2, "3", 4, 5]
 
json_build_object(VARIADIC "any") json Builds a JSON array out of a variadic argument list. By convention, the object is constructed out of alternating name/value arguments. SELECT json_build_object('foo',1,'bar',2);
   json_build_object
------------------------
 {"foo" : 1, "bar" : 2}
 
json_object(text[]) json 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 name/value pairs, or two dimensions such that each inner array has exactly two elements, which are taken as a name/value pair. select * from json_object('{a, 1, b, "def", c, 3.5}') or select json_object('{{a, 1},{b, "def"},{c, 3.5}}')
              json_object
---------------------------------------
 {"a" : "1", "b" : "def", "c" : "3.5"}
 
json_object(keys text[], values text[]) json The two-argument form of JSON object takes keys and values pairwise from two separate arrays. In all other respects it is identical to the one-argument form. select json_object('{a, b}', '{1,2}');
      json_object
------------------------
 {"a" : "1", "b" : "2"}
 

Table 9-43 shows the functions that are available for processing json and jsonb values. (see Section 8.14)

Table 9-43. JSON Processing Functions

FunctionReturn TypeDescriptionExampleExample Result

json_array_length(json)

jsonb_array_length(jsonb)

int Returns the number of elements in the outermost JSON array. json_array_length('[1,2,3,{"f1":1,"f2":[5,6]},4]')5

json_each(json)

jsonb_each(jsonb)

SETOF key text, value json

SETOF key text, value jsonb

Expands the outermost JSON object into a set of key/value pairs. select * from json_each('{"a":"foo", "b":"bar"}')
 key | value
-----+-------
 a   | "foo"
 b   | "bar"
 

json_each_text(from_json json)

jsonb_each_text(from_json jsonb)

SETOF key text, value text Expands the outermost JSON object into a set of key/value pairs. The returned value will be of type text. 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[])

jsonb_extract_path(from_jsonb jsonb, VARIADIC path_elems text[])

json

jsonb

Returns JSON value pointed to by path_elems. json_extract_path('{"f2":{"f3":1},"f4":{"f5":99,"f6":"foo"}}','f4'){"f5":99,"f6":"foo"}

json_extract_path_text(from_json json, VARIADIC path_elems text[])

json_extract_path_text(from_json jsonb, VARIADIC path_elems text[])

text Returns JSON value pointed to by path_elems. json_extract_path_text('{"f2":{"f3":1},"f4":{"f5":99,"f6":"foo"}}','f4', 'f6')foo

json_object_keys(json)

jsonb_object_keys(jsonb)

SETOF text Returns set of keys in the JSON object. Only the "outer" object will be displayed. json_object_keys('{"f1":"abc","f2":{"f3":"a", "f4":"b"}}')
 json_object_keys
------------------
 f1
 f2

json_populate_record(base anyelement, from_json json, [, use_json_as_text bool=false])

jsonb_populate_record(base anyelement, from_json jsonb, [, use_json_as_text bool=false])

anyelement Expands the object in from_json to a row whose columns match the record type defined by base. Conversion will be best effort; columns in base with no corresponding key in from_json will be left null. When processing json, if a column is specified more than once, the last value is used. select * from json_populate_record(null::x, '{"a":1,"b":2}')
 a | b
---+---
 1 | 2

json_populate_recordset(base anyelement, from_json json, [, use_json_as_text bool=false])

jsonb_populate_recordset(base anyelement, from_json jsonb, [, use_json_as_text bool=false])

SETOF anyelement Expands the outermost set of objects in from_json to a set whose columns match the record type defined by base. Conversion will be best effort; columns in base with no corresponding key in from_json will be left null. When processing json, if a column is specified more than once, the last value is used. select * from json_populate_recordset(null::x, '[{"a":1,"b":2},{"a":3,"b":4}]')
 a | b
---+---
 1 | 2
 3 | 4
 

json_array_elements(json)

jsonb_array_elements(jsonb)

SETOF json

SETOF jsonb

Expands a JSON array to a set of JSON values. SELECT * FROM json_array_elements('[1,true, [2,false]]')
   value
-----------
 1
 true
 [2,false]

json_array_elements_text(json)

jsonb_array_elements_text(jsonb)

SETOF text Expands a JSON array to a set of text values. SELECT * FROM json_array_elements_text('["foo", "bar"]')
   value
-----------
 foo
 bar

json_typeof(json)

jsonb_typeof(jsonb)

text Returns the type of the outermost JSON value as a text string. The types are object, array, string, number, boolean, and null. (See note below regarding the distinction between a JSON null and a SQL NULL.) json_typeof('-123.4')number

json_to_record(json [, nested_as_text bool=false])

jsonb_to_record(jsonb [, nested_as_text bool=false])

record Returns an arbitrary record from a JSON object. As with all functions returning 'record', the caller must explicitly define the structure of the record when making the call. The input JSON must be an object, not a scalar or an array. If nested_as_text is true, the function coerces nested complex elements to text. Also, see notes below on columns and types. select * from json_to_record('{"a":1,"b":[1,2,3],"c":"bar"}',true) as x(a int, b text, d text)
 a |    b    | d 
---+---------+---
 1 | [1,2,3] | 
 

json_to_recordset(json [, nested_as_text bool=false])

jsonb_to_recordset(jsonb [, nested_as_text bool=false])

setof record Returns an arbitrary set of records from a JSON object. As with json_to_record, the structure of the record must be explicitly defined when making the call. However, with json_to_recordset the input JSON must be an array containing objects. nested_as_text works as with json_to_record. select * from json_to_recordset('[{"a":1,"b":"foo"},{"a":"2","c":"bar"}]',true) as x(a int, b text);
 a |  b
---+-----
 1 | foo
 2 |
 

Note: The json functions and operators can impose stricter validity requirements than the type's input functions. In particular, they check much more closely that any use of Unicode surrogate pairs to designate characters outside the Unicode Basic Multilingual Plane is correct.

Note: Many of these functions and operators will convert Unicode escapes in the JSON text to the appropriate UTF8 character when the database encoding is UTF8. In other encodings the escape sequence must be for an ASCII character, and any other code point in a Unicode escape sequence will result in an error. In general, it is best to avoid mixing Unicode escapes in JSON with a non-UTF8 database encoding, if possible.

Note: In json_to_record and json_to_recordset, type-coercion from the JSON is "best effort" and may not result in desired values for some types. JSON elements are matched to identical field names in the record definition, and elements which do not exist in the JSON will simply be NULL. JSON elements which are not defined in the record template will be omitted from the output.

Note: The hstore extension has a cast from hstore to json, so that converted hstore values are represented as JSON objects, not as string values.

Note: The json_typeof function's null return value should not be confused with a SQL NULL. While calling json_typeof('null'::json) will return null, calling json_typeof(NULL::json) will return a SQL NULL.

See also Section 9.20 about the aggregate function json_agg which aggregates record values as JSON efficiently, and the aggregate function json_object_agg, which aggregates pairs of values into a JSON object.