arrays - 在 JSON 列类型中查找数组的最后一个元素

标签 arrays json postgresql

以下是在 Postgres 9.4.4 中以 json 数据类型存储的数据示例:

[
  1479772800000,
  70.12
],
[
  1479859200000,
  70.83
],
[
  1480032000000,
  71.23
]

如何选择此数组的最后一个元素:[1480032000000,71.23]

 \d stocks
                                     Table "public.stocks"
      Column      |         Type         |                      Modifiers                      
------------------+----------------------+-----------------------------------------------------
 id               | integer              | not null default nextval('stocks_id_seq'::regclass)
 ticker           | character varying(6) |  
 price_history    | json                 | 
Indexes:
    "stocks_pkey" PRIMARY KEY, btree (id)
    "ix_stocks_ticker" UNIQUE, btree (ticker)

最佳答案

您可以通过以下方式获取 Postgres JSON 数组的最后一个元素(已知在 Postgres 9.5+ 中有效):

select '...'::json->-1;

这使用 -> 运算符。负整数从末尾开始计数。

例如:

select '[[1479772800000, 70.12], [1479859200000, 70.83], [1480032000000, 71.23]]'::json->-1;

关于arrays - 在 JSON 列类型中查找数组的最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40825114/

相关文章:

jquery - 如何通过html表单使用jquery、json和ajax?

javascript - 在 JSON 对象上使用 stringify 以在 HTML 数据属性中使用

postgresql - pg_dumpall - Azure Database for PostgreSQL - 数据库 "azure_maintenance"的权限被拒绝

arrays - 在 Excel 中检索模式数组的值

javascript - 如何将数组值单独传递给函数?

php - 在 PHP 中,如何删除对象数组中的重复项,其中重复项定义为具有相同值的键值对的子集

python - 对 numpy 数组的所有值执行操作,引用 i 和 j

JSON、AJAX、REST 术语

macos - 在 osx-Lion 中创建并在 osx-snow-leopard 中访问的 postgres 9.1.3 数据的控制文件错误校验和不正确

javascript - 如何在分布式环境中处理 PostgreSQL 触发器