源:http://www.oschina.net/question/12_106368?sort=default&p=2#answers
评:
Postgres 9.3 目前正在紧锣密鼓的开发中,该版本值得关注的一个新特性就是 JSON 数据类型。在看完 new functions for data generation 这篇文章后,我们来看看在 commit 记录中关于新的 JSON 特性的说明:
commit a570c98d7fa0841f17bbf51d62d02d9e493c7fcc
Author: Andrew Dunstan
Date: Fri Mar 29 14:12:13 2013 -0400
Add new JSON processing functions and parser API.
The JSON parser is converted into a recursive descent parser, and
exposed for use by other modules such as extensions. The API provides
hooks for all the significant parser event such as the beginning and end
of objects and arrays, and providing functions to handle these hooks
allows for fairly simple construction of a wide variety of JSON
processing functions. A set of new basic processing functions and
operators is also added, which use this API, including operations to
extract array elements, object fields, get the length of arrays and the
set of keys of a field, deconstruct an object into a set of key/value
pairs, and create records from JSON objects and arrays of objects.
Catalog version bumped.
Andrew Dunstan, with some documentation assistance from Merlin Moncure.
基于存储的 JSON 数据,该提交还引入新的 API、运算符和函数用来操作 JSON 数据,共有 4 个运算符和8个新的函数,本文只简单介绍 4 个新的运算符。
下列的数据集用于文章中所有实验:
1
postgres=# CREATE TABLE aa (a int, b json);
2
CREATE TABLE
3
postgres=# INSERT INTO aa VALUES (1, '{"f1":1,"f2":true,"f3":"Hi I''m \"Daisy\""}');
4
INSERT 0 1
5
postgres=# INSERT INTO aa VALUES (2, '{"f1":{"f11":11,"f12":12},"f2":2}');
6
INSERT 0 1
7
postgres=# INSERT INTO aa VALUES (3, '{"f1":[1,"Robert \"M\"",true],"f2":[2,"Kevin \"K\"",false]}');
8
INSERT 0 1
第一个运算符是 “->”, 用来直接从 JSON 数据库获取字段值,使用文本值来标注字段的键:
1
postgres=# SELECT b->'f1' AS f1, b->'f3' AS f3 FROM aa WHERE a = 1;
2
f1 | f3
3
----+--------------------
4
1 | "Hi I'm \"Daisy\""
5
(1 row)
也可以使用多个键来获取数据或者另外一个子集数据:
01
postgres=# SELECT b->'f1'->'f12' AS f12 FROM aa WHERE a = 2;
02
f12
03
-----
04
12
05
(1 row)
06
postgres=# SELECT b->'f1' AS f1 FROM aa WHERE a = 2;
07
f1
08
---------------------
09
{"f11":11,"f12":12}
10
(1 row)
另外一个更有趣的方法,当使用整数作为键时,你可直接从存储的数组获取数据:
1
postgres=# SELECT b->'f1'->0 as f1_0 FROM aa WHERE a = 3;