Funciones de proceso de JSON

Obtener información sobre las funciones que están disponibles para procesar los valores json y jsonb.

jsonb_array_length
Tipo de retorno: int
Devuelve el número de elementos de la matriz JSON más externa.
Ejemplos:
  • SELECT jsonb_array_length('[1,2,3,{"f1":1,"f2":[5,6]},4]');
     JSONB_ARRAY_LENGTH 
    --------------------
                      5
    (1 row)
  • SELECT jsonb_array_length('["一",2,3,{"二":1,"三":[5,6]},4, "四"]');
     JSONB_ARRAY_LENGTH 
    --------------------
                      6
    (1 row)
  • SELECT jsonb_array_length('{"f1":1,"f2":[5,6]}');
    ERROR:  cannot get array length of a non-array
    
  • SELECT jsonb_array_length('4');
    ERROR:  cannot get array length of a scalar
json_extract_path | jsonb_extract_path
json_extract_path(from_json json, path_elems jsonb array)

jsonb_extract_path(from_json jsonb, path_elems jsonb array)

Tipo de retorno: json, jsonb
Devuelve el valor JSON al que apunta path_elems. Equivale al operador " #> ".
Ejemplos:
  • SELECT json_extract_path('["a", "foo", "baz"]', '[0]');
     JSON_EXTRACT_PATH 
    -------------------
     "a"
    (1 row)
  • SELECT json_extract_path('[{"a":"foo"},{"b":"bar"},{"c":"baz"}]', '[0]');
     JSON_EXTRACT_PATH 
    -------------------
     {"a": "foo"}
    (1 row)
  • SELECT jsonb_extract_path('["a", "foo", "baz"]', '[0]');
     JSONB_EXTRACT_PATH 
    --------------------
     "a"
    (1 row)
  • SELECT jsonb_extract_path('[{"a":"foo"},{"b":"bar"},{"c":"baz"}]', '[0,"a"]');
     JSONB_EXTRACT_PATH 
    --------------------
     "foo"
    (1 row)
json_extract_path_text(from_json json, VARIADIC path_elems jsonb array) | jsonb_extract_path_text(from_json jsonb, VARIADIC path_elems jsonb array)
Tipo de retorno: text
Devuelve (como texto) el valor JSON al que apunta path_elems. Equivale al operador " #>> ".
Ejemplos:
  • SELECT json_extract_path_text('{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}','["f4","f6"]');
     JSON_EXTRACT_PATH_TEXT 
    ------------------------
     stringy
    (1 row)
  • SELECT json_extract_path_text('{"f2":{"f3":1},"f4":{"f5":99,"f6":"stringy"}}','["f2"]');
     JSON_EXTRACT_PATH_TEXT 
    ------------------------
     {"f3": 1}
    (1 row)
  • SELECT jsonb_extract_path('["a", "foo", "baz"]', '[0]');
     JSONB_EXTRACT_PATH 
    --------------------
     "a"
    (1 row)
  • SELECT jsonb_extract_path('[{"a":"foo"},{"b":"bar"},{"c":"baz"}]', '[0]');
     JSONB_EXTRACT_PATH 
    --------------------
     {"a": "foo"}
    (1 row)
jsonb_typeof(jsonb)
Tipo de retorno: text
Devuelve el tipo del valor JSON más externo como una serie de texto. Los tipos posibles son objeto, matriz, serie, número, booleano y nulo.
Ejemplos:
  • SELECT jsonb_typeof('{}') AS object;
     OBJECT 
    --------
     object
    (1 row)
  • SELECT jsonb_typeof('[]') AS array;
     ARRAY 
    -------
     array
    (1 row)
  • SELECT jsonb_typeof('null') AS "null";
     null 
    ------
     null
    (1 row)
  • SELECT jsonb_typeof('1') AS number;
     NUMBER 
    --------
     number
    (1 row)
jsonb_strip_nulls(from_json jsonb)
Tipo de retorno: jsonb
Devuelve from_json con todos los campos de objeto que tienen valores nulos omitidos. Los otros valores nulos se ven afectados, se quedan tal cual.

Si el argumento de json_strip_nulls contiene nombres de campo duplicados en algún objeto, el resultado podría ser semánticamente diferente, en función del orden en el que se produzcan. Esto no es un problema para ' jsonb_strip_nulls ya que los valores de ' jsonb ' nunca tienen nombres de campo objeto duplicados.

Ejemplos:
  • SELECT jsonb_strip_nulls('[1,2,null,3,4]');
     JSONB_STRIP_NULLS  
    --------------------
     [1, 2, null, 3, 4]
    (1 row)
  • SELECT jsonb_strip_nulls('[1,{"a":1,"b":null,"c":2},3]');
        JSONB_STRIP_NULLS     
    --------------------------
     [1, {"a": 1, "c": 2}, 3]
    (1 row)
  • SELECT jsonb_strip_nulls('{"空值": {"空值 1": null, "空值 2": null}, "没有": {} }');
        JSONB_STRIP_NULLS     
    --------------------------
     {"没有": {}, "空值": {}}
    (1 row)
  • SELECT jsonb_strip_nulls('{"a": {"b": null, "c": null}, "d": {} }');
     JSONB_STRIP_NULLS  
    --------------------
     {"a": {}, "d": {}}
    (1 row)
jsonb_set(target jsonb, path jsonb array, new_value jsonb [, create_missing boolean])
Tipo de retorno: jsonb
Devuelve target con la sección designada por ruta reemplazada por ' new_value, o con ' new_value ' añadido si create_missing ' es verdadero (por defecto es verdadero) y el elemento designado por ruta no existe. Al igual que con los operadores orientados a la vía de acceso, los enteros negativos que aparecen en la vía de acceso cuentan desde el final de las matrices JSON.
Ejemplos:
  • SELECT jsonb_set('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}', '["n"]'    , '[1,2,3]');
                                    JSONB_SET                                 
    --------------------------------------------------------------------------
     {"a": 1, "b": [1, 2], "c": {"1": 2}, "d": {"1": [2, 3]}, "n": [1, 2, 3]}
    (1 row)
  • SELECT jsonb_set('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}', '["b",-1]' , '[1,2,3]');
                                      JSONB_SET                                  
    -----------------------------------------------------------------------------
     {"a": 1, "b": [1, [1, 2, 3]], "c": {"1": 2}, "d": {"1": [2, 3]}, "n": null}
    (1 row)
  • SELECT jsonb_set('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}', '["d",1,0]', '[1,2,3]');
                                      JSONB_SET                                  
    -----------------------------------------------------------------------------
     {"a": 1, "b": [1, 2], "c": {"1": 2}, "d": {"1": [[1, 2, 3], 3]}, "n": null}
    (1 row)
  • SELECT jsonb_set('{"n":null, "a":1, "b":[1,2], "c":{"1":2}, "d":{"1":[2,3]}}', '["n"]'    , '{"1": 2}');
                                    JSONB_SET                                
    -------------------------------------------------------------------------
     {"a": 1, "b": [1, 2], "c": {"1": 2}, "d": {"1": [2, 3]}, "n": {"1": 2}}
    (1 row)
jsonb_insert(target jsonb, path jsonb array, new_value jsonb [, insert_after boolean])
Tipo de retorno: jsonb
Devuelve el destino con new_value insertado. Si la sección de destino designada por la vía de acceso está en una matriz JSONB, new_value se insertará antes o después del destino, según si insert_after es true (el valor predeterminado es false). Si la sección de destino designada por la vía de acceso está en el objeto JSONB, new_value sólo se insertará si el destino no existe. Al igual que con los operadores orientados a la vía de acceso, los enteros negativos que aparecen en la vía de acceso cuentan desde el final de las matrices JSON.
Ejemplos:
  • SELECT jsonb_insert('{"a": [0,1,2]}', '["a", 1]', '"new_value"');
             JSONB_INSERT          
    -------------------------------
     {"a": [0, "new_value", 1, 2]}
    (1 row)
  • SELECT jsonb_insert('{"a": [0,1,2]}', '["a", 1]', '"new_value"', true);
             JSONB_INSERT          
    -------------------------------
     {"a": [0, 1, "new_value", 2]}
    (1 row)
  • SELECT jsonb_insert('{"a": {"b": {"c": [0, 1, "test1", "test2"]}}}', '["a", "b", "c", 2]', '"new_value"');
                            JSONB_INSERT                        
    ------------------------------------------------------------
     {"a": {"b": {"c": [0, 1, "new_value", "test1", "test2"]}}}
    (1 row)
  • SELECT jsonb_insert('{"a": {"b": {"c": [0, 1, "test1", "test2"]}}}', '["a", "b", "c", 2]', '"new_value"', true);
                            JSONB_INSERT                        
    ------------------------------------------------------------
     {"a": {"b": {"c": [0, 1, "test1", "new_value", "test2"]}}}
    (1 row)
jsonb_pretty(from_json jsonb)
Tipo de retorno: text
Devuelve from_json como texto JSON indentado.
Ejemplos:
  • SELECT jsonb_pretty('{"a": "test", "b": [1, 2, 3], "c": "test3", "d":{"dd": "test4", "dd2":{"ddd": "test5"}}}');
                                                                                          JSONB_PRETTY                                                                                      
    ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
     {
        "a": "test",
        "b": [
            1,
            2,
            3
        ],
        "c": "test3",
        "d": {
            "dd": "test4",
            "dd2": {
                "ddd": "test5"
            }
        }
    }
    (1 row)
  • SELECT jsonb_pretty('[{"f1":1,"f2":null},2,null,[[{"x":true},6,7],8],3]');
                                                                                                    JSONB_PRETTY                                                                                                 
    -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
     [
        {
            "f1": 1,
            "f2": null
        },
        2,
        null,
        [
            [
                {
                    "x": true
                },
                6,
                7
            ],
            8
        ],
        3
    ]
    (1 row)
  • SELECT jsonb_pretty('{"a":["b", "c"], "d": {"e":"f"}}');
                                       JSONB_PRETTY                                   
    ----------------------------------------------------------------------------------
     {
        "a": [
            "b",
            "c"
        ],
        "d": {
            "e": "f"
        }
    }
    (1 row)
  • SELECT jsonb_pretty('{"数":["二十七", "二十八"], "雇员": {"职称":"电气工程师"}}');
                                                    JSONB_PRETTY                                                
    ------------------------------------------------------------------------------------------------------------
     {
        "数": [
            "二十七",
            "二十八"
        ],
        "雇员": {
            "职称": "电气工程师"
        }
    }
    (1 row)