代码之家  ›  专栏  ›  技术社区  ›  DDave

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

  •  16
  • DDave  · 技术社区  · 7 年前

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

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

    大多数人不“使用”::jsonb“like如图所示:

    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,对象数组不是一个对象,但我不知道postresql的jsonb是否接受

    {电话:[{“type”:“mobile”,“phone”:“001001”}, {“type”:“fix”,“phone”:“002002”}]}

    2 回复  |  直到 7 年前
        1
  •  28
  •   Yuci    5 年前

    示例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. 确保用双引号将键和值括起来。
        2
  •  5
  •   Vao Tsun    7 年前

    '{}' 是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
    

    或:

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