For example with have this code:
var json = { "user1" : { "id" : 3 }, "user2" : { "id" : 6 }, "user3" : { "id" : 1 } }
How can I sort this json to be like this -
var json = { "user3" : { "id" : 1 }, "user1" : { "id" : 3 }, "user2" : { "id" : 6 } }
I sorted the users with the IDs..
I don't know how to do this in javascript..
JSON return type is an array of objects. Hence sort method cannot be used directly to sort the array. However, we can use a comparer function as the argument of the 'sort' method to get the sorting implemented.
Using json. dumps() function is one way to sort the JSON object. It is used to convert the array of JSON objects into a sorted JSON object. The value of the sort_keys argument of the dumps() function will require to set True to generate the sorted JSON objects from the array of JSON objects.
A JSONArray can parse text from a String to produce a vector-like object and supports java. util. List interface. We can sort a JSONArray in the below example.
The JSON Data Interchange Standard definition at json.org specifies that “An object is an unordered [emphasis mine] set of name/value pairs”, whereas an array is an “ordered collection of values”. In other words, by definition the order of the key/value pairs within JSON objects simply does not, and should not, matter.
First off, that's not JSON. It's a JavaScript object literal. JSON is a string representation of data, that just so happens to very closely resemble JavaScript syntax.
Second, you have an object. They are unsorted. The order of the elements cannot be guaranteed. If you want guaranteed order, you need to use an array. This will require you to change your data structure.
One option might be to make your data look like this:
var json = [{ "name": "user1", "id": 3 }, { "name": "user2", "id": 6 }, { "name": "user3", "id": 1 }];
Now you have an array of objects, and we can sort it.
json.sort(function(a, b){ return a.id - b.id; });
The resulting array will look like:
[{ "name": "user3", "id" : 1 }, { "name": "user1", "id" : 3 }, { "name": "user2", "id" : 6 }];
Here is a simple snippet that sorts a javascript representation of a Json.
function isObject(v) { return '[object Object]' === Object.prototype.toString.call(v); }; JSON.sort = function(o) { if (Array.isArray(o)) { return o.sort().map(JSON.sort); } else if (isObject(o)) { return Object .keys(o) .sort() .reduce(function(a, k) { a[k] = JSON.sort(o[k]); return a; }, {}); } return o; }
It can be used as follows:
JSON.sort({ c: { c3: null, c1: undefined, c2: [3, 2, 1, 0], }, a: 0, b: 'Fun' });
That will output:
{ a: 0, b: 'Fun', c: { c2: [3, 2, 1, 0], c3: null } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With