26

I have this update, i've read postgresql documentation, but nothing clear about how to insert data, some tutorials options:

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

and most dont' use '::jsonb' like is indicated on:

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

here my code:

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

I get this error:

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

I need just record a lit of phones, need to enclose in a big name object like? I mean for javascript , array of objets is not an object, but i dont know if that is accepted in jsonb of postresql

{ phones:[ {"type": "mobile", "phone": "001001"} , {"type": "fix", "phone": "002002"} ] }

Vao Tsun
  • 47,234
  • 13
  • 100
  • 132
DDave
  • 1,400
  • 3
  • 16
  • 33

2 Answers2

46

Example 1 (object):

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';

Example 2 (array):

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

Notes:

  1. My PostgreSQL version
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. Be sure to enclose the keys and values with double quotes.
Yuci
  • 27,235
  • 10
  • 114
  • 113
  • Perfect Answer. can you please tell me how to store point(longitude, latitude) in PostgreSQL – Irshad Khan Sep 10 '20 at 10:56
  • 1
    @IrshadKhan PostGIS might be your answer, which is a Spatial and Geographic Objects for PostgreSQL: https://stackoverflow.com/questions/8150721/which-data-type-for-latitude-and-longitude – Yuci Sep 10 '20 at 11:11
7

'{}' is array type in postgres. if you use jsonb, use regular '[]' for array:

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

or:

so=# select jsonb_pretty('[ {"type": "mobile", "phone": "001001"} , {"type": "fix", "phone": "002002"} ]');
jsonb_pretty
[
    {
        "type": "mobile",
        "phone": "001001"
    },
    {
        "type": "fix",
        "phone": "002002"
    }
]
(1 row)
Vao Tsun
  • 47,234
  • 13
  • 100
  • 132