I'm trying to create JSON object by passing to json_object() two arrays. One with keys, second with JSON(or JSONB) objects. So as to put JSON as value for predefined key.
The signature of json_object() function is json_object(varchar[], varchar[]) but in my case I have json_object(varchar[], json[]). The issue is when I'm typecasting json_object(varchar[], json[]::varchar[]) stringification creates escaped string for json element and postgress does not recognize value as nested JSON, but instead thinks that is string value.
SELECT
json_object(
ARRAY[set_of_keys::varchar],
ARRAY[set_of_values::json],
) as some_column
gives error function json_object(varchar[], json[]) does not exist
SELECT
json_object(
ARRAY[set_of_keys::varchar],
ARRAY[set_of_values::json]::varchar[],
) as some_column
lead to esacaped stringification of set_of_values.
How to put these objects as a value without stringification?
Sample data:
SELECT
json_object(
ARRAY['a', 'b', 'c'],
ARRAY['{"key1":"value1"}'::json, '{"key2": "value2"}'::json, '{"key3": "value3", "key4":"value4"}'::json]::varchar[]
)
I would like to get rid of ::varchar[] typecasting at the end of second array.
ARRAYis a Postgres array not a JSON array. See JSON section 8.14.1. JSON Input and Output Syntax and JSON functions Table 9.46. JSON Creation Functions. Be aware that there are two JSON types,jsonandjsonb.jsonbthe code is forjson_objectwhich producesjsontype.ARRAYofjsonvalues and turning it into a PostgresvarcharARRAYwhich is why you are getting the escaped stringification.