Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql 5.7 native json support - control keys order in json_insert function

Tags:

json

mysql-5.7

I am facing issues with json key ordering while inserting using json_insert function.

I have the sorted records as below

"AIR", "AIR Express"

"CFR", "Cost and Freight"

"FH", "Free house"

"UN", "United Nations"

"UPS", "United Parcel Service"

After converting the above records into json using json_insert function, I am seeing the results as below

{"FH":"Free house", "UN": "United Nations", "AIR": "AIR Express", "CFR": "Cost and Freight", "UPS": "United Parcel Service"}

but I want the json to maintain the keys in the order I am inserting. Though I could sense that it is trying to maintain the order based on the character length of keys. But how can I get rid to get the keys aligned in the order.

like image 267
Manikanda Prabu Avatar asked Aug 12 '16 05:08

Manikanda Prabu


People also ask

Does MySQL 5.7 support JSON data type?

Unless otherwise indicated, the JSON functions were added in MySQL 5.7. 8. A set of spatial functions for operating on GeoJSON values is also available.

Does MySQL 5.6 support JSON data type?

Yes , you can definitely to it using JSON_EXTRACT() function in mysql.

What is JSON extract () function in MySQL?

We can use the JSON_EXTRACT function to extract data from a JSON field. The basic syntax is: JSON_EXTRACT(json_doc, path) For a JSON array, the path is specified with $[index] , where the index starts from 0: mysql> SELECT JSON_EXTRACT('[10, 20, 30, 40]', '$[0]'); +------------------------------------------+

What is the drawback of JSON columns in MySQL?

The drawback? If your JSON has multiple fields with the same key, only one of them, the last one, will be retained. The other drawback is that MySQL doesn't support indexing JSON columns, which means that searching through your JSON documents could result in a full table scan.


1 Answers

That's sad, but at now is no way to keep original keys order.

Normalization, Merging, and Autowrapping of JSON Values

The normalization performed by MySQL also sorts the keys of a JSON object (for the purpose of making lookups more efficient). The result of this ordering is subject to change and not guaranteed to be consistent across releases. In addition, extra whitespace between keys, values, or elements in the original document is discarded.

like image 67
gzzz Avatar answered Oct 14 '22 03:10

gzzz