Overview

json_object extension

This small extension for PostgreSQL 9.2 and up provides a function that takes a one- or two-dimensional SQL array of text and turns it into a JSON object.

If the array has one dimension it must have an even number of elements, and if it has two dimensions the inner dimension must be 2.

Null and empty keys are forbidden, but it is the caller's reponsibility to ensure that keys are not repeated.

All non-null values are rendered as strings, including values which might be numeric or boolean. Null values are rendered as 'nil'.

Examples:

SELECT json_object('{a,1,b,2,3,NULL,"d e f","a b c"}');
                      json_object                      
-------------------------------------------------------
 {"a" : "1", "b" : "2", "3" : null, "d e f" : "a b c"}
(1 row)

-- same but with two dimensions
SELECT json_object('{{a,1},{b,2},{3,NULL},{"d e f","a b c"}}');
                      json_object                      
-------------------------------------------------------
 {"a" : "1", "b" : "2", "3" : null, "d e f" : "a b c"}
(1 row)

Credit

This work was supported by IVC.