加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何插入Postgresql JSON数组

发布时间:2020-12-13 16:01:48 所属栏目:百科 来源:网络整理
导读:表定义是: chat_id serial primary key,last_update timestamp,messages JSON[] 我想插入这样的记录: insert into chats (messages) values ('{{"sender":"pablo","body":"they are on to us"}}'); 有错误: ERROR: malformed array literal: “{{“sender
表定义是:

chat_id serial primary key,last_update timestamp,messages JSON[]

我想插入这样的记录:

insert into chats (messages) values ('{{"sender":"pablo","body":"they are on to us"}}');

有错误:

ERROR: malformed array literal: “{{“sender”:”pablo”,”body”:”they are on to us”}}”
LINE 1: insert into chats (messages) values (‘{{“sender”:”pablo”,”bo…

我也试过这种方法:

insert into chats (messages) values (ARRAY('{"sender":"pablo","body":"they are on to us"}'));

请注意,更新行并使用array_append插入工作正常.

解决方法

我认为这是JSON符号之间的冲突,它以{和Postgres中的短手数组符号开头,其中数组的字符串表示也用{表示.

以下作品:

insert into chats 
  (messages) 
values 
  (array['{"sender":"pablo","body":"they are on to us"}']::json[]);

这避免了{{通过使用显式数组构造函数的歧义.

要使数组成为json数组,您需要将字符串转换为json或将结果数组转换为json [](请参阅上面的示例).如果在该行中有多个JSON文档,则转换整个数组会更容易:

insert into chats 
  (messages) 
values 
  (array['{"sender":"pablo","body":"they are on to us"}',{"sender":"arthur"}']::json[]);

或者:

insert into chats 
  (messages) 
values 
  (array['{"sender":"pablo","body":"they are on to us"}'::json,{"sender":"arthur"}'::json]);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读