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

DDa*_*ave 10 sql postgresql json jsonb

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

1.with '{}'
2.with {}
3.with '[]'  <-- array of objects
Run Code Online (Sandbox Code Playgroud)

并且大多数不'使用':: 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';
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

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
Run Code Online (Sandbox Code Playgroud)

我只需要录制一盏电话,需要附上一个大名鼎鼎的对象吗?我的意思是对于 javascript ,对象数组不是对象,但我不知道 postresql 的 jsonb 是否接受它

{手机:[ {“type”:“mobile”,“phone”:“001001”},{“type”:“fix”,“phone”:“002002”}]}

Yuc*_*uci 21

示例 1(对象):

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

示例 2(数组):

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

笔记:

  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
Run Code Online (Sandbox Code Playgroud)
  1. 确保用双引号将键和值括起来。


Vao*_*sun 5

'{}'是 postgres 中的数组类型。如果使用jsonb,请使用常规'[]'数组:

so=# select jsonb_pretty('{"phones":[ {"type": "mobile", "phone": "001001"} , {"type": "fix", "phone": "002002"} ] }');
jsonb_pretty
{
    "phones": [
        {
            "type": "mobile",
            "phone": "001001"
        },
        {
            "type": "fix",
            "phone": "002002"
        }
    ]
}
(1 row)
Time: 0.486 ms
Run Code Online (Sandbox Code Playgroud)

或者:

so=# select jsonb_pretty('[ {"type": "mobile", "phone": "001001"} , {"type": "fix", "phone": "002002"} ]');
jsonb_pretty
[
    {
        "type": "mobile",
        "phone": "001001"
    },
    {
        "type": "fix",
        "phone": "002002"
    }
]
(1 row)
Run Code Online (Sandbox Code Playgroud)