Graphql-engine: Order of `jsonb` keys not respected in insert input

Created on 28 Sep 2020  路  6Comments  路  Source: hasura/graphql-engine

Screenshot 2020-09-28 at 13 03 22

Order of keys should be the same in db as in the json input.

Tested in 1.3.0 & 1.3.2.

question

All 6 comments

@KATT You'll have to use the json type.

From Postgres docs:

Because the json type stores an exact copy of the input text, it will preserve semantically-insignificant white space between tokens, as well as the order of keys within JSON objects. Also, if a JSON object within the value contains the same key more than once, all the key/value pairs are kept. (The processing functions consider the last value as the operative one.) 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.

Oh okay, thanks!

I just did a migration and assumed it worked based on your comment @0x777, but it wasn't enough.

Have a look at https://hot-foal-53.hasura.app/console

Query

mutation test($json: json!) {
  insert_post_one(object: {json:$json}) {
    id
    json
  }
}

Variables

{
  "json":{
    "first entry": 1,
    "second entry": 2,
    "third entry": 3
  }
}

Response

{
  "data": {
    "insert_post_one": {
      "id": "72b7c435-0d84-41e2-a003-ca91506476c8",
      "json": {
        "third entry": 3,
        "first entry": 1,
        "second entry": 2
      }
    }
  }
}

Screenshots

Screenshot 2020-09-30 at 17 30 41 Screenshot 2020-09-30 at 17 31 24

Bump

@KATT Turns out json values get parsed while moving through the system and can lose their ordering. The JSON spec doesn't guarantee preservation of ordering and hence most libraries treat them as unordered maps.

Unfortunately, there is nothing much we can do about this. If input order preservation is really important for your application, then a workaround could be to store them as stringified JSON and parse them in client. Definitely not ideal but still a workaround.

The key order of json which comes from a handler response for an action is changed by hasura either.

Was this page helpful?
0 / 5 - 0 ratings