Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid duplicate values in a PostgreSQL JSON data type?

I have the next example code:

CREATE TABLE books ( id integer, data json );

INSERT INTO books VALUES (1,
  '{ id: 1,id: 1,"name": "Book the First" }');

You can see that id is a field within the format JSON that's duplicated, I understand that PostgreSQL have some feature that avoid that issue, but I can not find it.

like image 349
EmerBallen Avatar asked Jul 23 '26 19:07

EmerBallen


1 Answers

JSONB will do this automatically: http://www.postgresql.org/docs/9.5/static/datatype-json.html

By contrast, jsonb does not preserve white space, does not preserve the order of object keys, and does not keep duplicate object keys. If duplicate keys are specified in the input, only the last value is kept.

So just use 9.4 and above and change your table column to jsonb:

CREATE TABLE books ( id integer, data jsonb );

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!