3

The reordering of Json-Content is already an known issue while sending AJAX Request, but I wasn't aware that the same happens while inserting Json-content into an Mysql Table with JSON type.

In this case the mysql server also orders its content before saving.

before:

{"c":3, "b":2, "a":1}

after:

{"a":1, "b":2, "c":3}

Suppose I would like to prevent this ordering for some purpose... Is there any possibility to disable the ordering without adapting the Json data itself?

Christian Felix
  • 644
  • 1
  • 9
  • 28
  • What do you mean by *json ordering*? Please provide a few examples of what you are seeing. – GMB Apr 30 '20 at 08:03
  • JSON datatype is stored in some internal format, so back reconstruction may reorder its components. The only way to avoid this is in store JSON in a field of string type. – Akina Apr 30 '20 at 08:13
  • @Akina, storing json in string is non of our options, as we are using the mysql json function to query the data. – Christian Felix Apr 30 '20 at 08:16
  • Please see this question, I think it's same with your issue https://stackoverflow.com/questions/48382457/mysql-json-column-change-array-order-after-saving – Widada Apr 30 '20 at 08:16
  • @Widada, you right. but seems to be unanswered yet. just to contact 3rd party is not what I am looking for. – Christian Felix Apr 30 '20 at 08:19
  • 1
    Nevertheless - either string datatype and storing order (which makes no sense except the positional order of array elements) or JSON datatype and possible reordering. *we are using the mysql json function to query the data.* JSON functions may easily accept string datatype arguments if they're valid JSON values. – Akina Apr 30 '20 at 08:20
  • @ChristianFelix: the ordering of key/value pairs in a json object is not meaningful - these are basically unordered, so your database, as well as your web server, are free to change it. Why do you specifically want to preserve it? – GMB Apr 30 '20 at 08:29

1 Answers1

2

The key to this is to serialize this > then store it > retrieve > then parse

For example: First store object as a string

var jsonDataStringed = JSON.stringify(myJsonData);
INSERT INTO MY_TABLE(id,jsonDataStringed);

then to retrieve the string and change it back to object

db.sequelize.query(`SELECT * FROM MY_TABLE`);
var myJsonData = JSON.parse(db[0])
Michael Nelles
  • 5,426
  • 8
  • 41
  • 57