sql - 在 postgresql、选项数组或对象中插入 jsonb 数据,有效方式

标签 sql json postgresql jsonb

我有此更新,我已阅读 postgresql 文档,但不清楚如何插入数据,一些教程选项:

1.with '{}'
2.with {}
3.with '[]'  <-- array of objects

而且大多数人不使用 '::jsonb' ,如上所示:

https://www.postgresql.org/docs/9.4/static/datatype-json.html

这里是我的代码:

 UPDATE customer set phones ='{  {"type": "mobile", "phone": "001001"} ,
{"type": "fix", "phone": "002002"}  }'::jsonb  
  where id ='4ca27243-6a55-4855-b0e6-d6e1d957f289';

我收到这个错误:

ERROR:  invalid input syntax for type json
LINE 1: UPDATE customer set phones ='{  {"type": "mobile", "phone": ...
                                    ^
DETAIL:  Expected string or "}", but found "{".
CONTEXT:  JSON data, line 1: {  {...
SQL state: 22P02
Character: 29

我只需要记录一些电话,需要封装在一个大名称对象中吗?我的意思是对于 javascript,objets 数组不是对象,但我不知道 postresql 的 jsonb 是否接受它

{ phones:[ {"type": "mobile", "phone": "001001"} , {“类型”:“修复”,“电话”:“002002”}]}

最佳答案

示例 1(对象):

CREATE TABLE customer {
  contact JSONB
}
update customer
set contact = '{ "phones":[ {"type": "mobile", "phone": "001001"} , {"type": "fix", "phone": "002002"} ] }'
where id = '4ca27243-6a55-4855-b0e6-d6e1d957f289';

例子2(数组):

CREATE TABLE customer {
  phones JSONB
}
update customer
set phones = '[ {"type": "mobile", "phone": "001001"} , {"type": "fix", "phone": "002002"} ]'
where id = '4ca27243-6a55-4855-b0e6-d6e1d957f289';

注意事项:

  1. 我的 PostgreSQL 版本
select version();

PostgreSQL 11.2 (Debian 11.2-1.pgdg90+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 6.3.0-18+deb9u1) 6.3.0 20170516, 64-bit
  1. 一定要用双引号将键和值括起来。

关于sql - 在 postgresql、选项数组或对象中插入 jsonb 数据,有效方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47131040/

相关文章:

json - 在 Postgresql 中查询复杂 JSON 的简洁方法

mysql - 大表复杂查询

带有派生表的 SQL Server 查询产生语法错误

java - 如何使用 Hibernate\Spring Data 将 json 转换为 java 对象数据并保存到数据库中?

javascript - 如何实现Google饼图(带有图例显示和相应的值)

postgresql - 在 Postgresql 中加入的选择结果中的重复条目

sql - 使一对多关系看起来像一对一

sql - 更新语句 Sql Access 双内连接

python - Django Rest Framework 不序列化 SerializerMethodField

sql - Postgres 选择数组具有相等值但没有特定顺序的位置