francs=> select id ,name ->>'col1'col1, name ->> 'col2'col2, name ->> 'col3' col3 from test_json1 where id=1; id | col1 | col2 | col3 ----+------+--------+------ 1 | 1 | francs | male (1 row)
francs=> select * from test_json1 where id=1; id | name ----+------------------------------------------ 1 | {"col1":1,"col2":"francs","col3":"male"} (1 row) francs=> select * from json_each((select name from test_json1 where id=1)); key | value ------+---------- col1 | 1 col2 | "francs" col3 | "male" (3 rows) francs=> select * from json_each('{"a":"foo", "b":"bar"}'); key | value -----+------- a | "foo" b | "bar" (2 rows)
2.2 json_each_text(json) 函数
1 2 3 4 5 6 7
francs=> select * fromjson_each_text((select name from test_json1 where id=1)); key | value ------+-------- col1 | 1 col2 | francs col3 | male (3 rows)
2.3 row_to_json 函数
1 2 3 4 5 6 7 8 9 10 11 12 13
francs=> select row_to_json(test_1) from test_1; row_to_json -------------------------------- {"id":1,"name":"a","flag":"f"} {"id":2,"name":"b","flag":"f"} {"id":3,"name":"c","flag":"t"} (3 rows) francs=> select row_to_json(test_1) from test_1 where id=1; row_to_json -------------------------------- {"id":1,"name":"a","flag":"f"} (1 row)
francs=> alter table test_json1 add grade int4 default'6'; ALTER TABLE francs=> select * from test_json1; id | name | grade ----+------------------------------------------+------- 1 | {"col1":1,"col2":"francs","col3":"male"} | 6 2 | {"col1":2,"col2":"fp","col3":"female"} | 6 (2 rows) francs=> selectjson_agg(name) from test_json1 groupby grade; json_agg ------------------------------------------------------------------------------------ [{"col1":1,"col2":"francs","col3":"male"}, {"col1":2,"col2":"fp","col3":"female"}] (1 row)
备注:结果很明显。
3.2 例2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
francs=> select * from test_1; id | name | flag ----+------+------ 1 | a | f 2 | b | f 3 | c | t (3 rows) francs=> select json_agg(a) from test_1 a; json_agg ----------------------------------- [{"id":1,"name":"a","flag":"f"}, + {"id":2,"name":"b","flag":"f"}, + {"id":3,"name":"c","flag":"t"}] (1 row)