Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort JSON alphabetically

Tags:

json

jquery

I have a JSON object generated based on data stored in a table. I then need to be able to sort it in different ways, but when I do JSON.stringify(array) and try to sort from there it doesn't work. When I try to just do array.sort(); it will change the order, but ultimately doesn't work. I don't have much experience with JSON and how to operate it so I'm not sure what else to try. After sorting it I need to go through and rewrite the table with the selected category in alphabetical order.

The JSON looks like this:

var arr = [{
"Functional Category":"T-Shirt",
"Brand Name":"threadless",
"When Obtained":"Last 3 Months",
"How Obtained":"Purchased",
"How Often Worn":"Monthly",
"Where It's Made":"India",
"Has a Graphic":"Yes"}]

I have a fiddle setup here: http://jsfiddle.net/Skooljester/88HVZ/1/ and I have tried what was suggested here but was unable to make it work.

I have two questions, one: how do I go about accomplishing this, and two: is there a better way to do the sorting?

like image 926
ayyp Avatar asked Dec 07 '11 16:12

ayyp


People also ask

Is JSON in alphabetical order?

The default type nlohmann::json uses a std::map to store JSON objects, and thus stores object keys sorted alphabetically.

How do I sort items in JSON?

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.

Can I sort a JSON file?

How do you use the JSON Sorter tool? Enter your JSON into the first text area, or drag and drop a file, after, select the sort method you're going to use, key value requires the key name (if not specified selects the first key), click the example button to get an idea on how it works.


3 Answers

see below code ....

function sortObject(o) {
    var sorted = {},
    key, a = [];

    for (key in o) {
        if (o.hasOwnProperty(key)) {
                a.push(key);
        }
    }

    a.sort();

    for (key = 0; key < a.length; key++) {
        sorted[a[key]] = o[a[key]];
    }
    return sorted;
}

Does that help?

like image 133
MANISHDAN LANGA Avatar answered Sep 18 '22 14:09

MANISHDAN LANGA


First, define a compare function:

function compare(el1, el2, index) {
  return el1[index] == el2[index] ? 0 : (el1[index] < el2[index] ? -1 : 1);
}

Then, to sort the array on the first column, use this:

array.sort(function(el1,el2){
  return compare(el1, el2, "Functional Category")
});

Or, to sort on the first column A-Z, and on the second column Z-A if the first column is equal:

array.sort(function(el1,el2){
  var compared = compare(el1, el2, "Functional Category")
  return compared == 0 ? -compare(el1, el2, "Brand Name") : compared;
});
like image 37
Bart Avatar answered Sep 19 '22 14:09

Bart


The Mozilla developer documentation has a helpful explanation of the sort function. You can provide a function as a parameter that tells the browser how to do the sort.

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort

Some pseudo-code from that link, with the myArray.sort call added and the function name removed:

myArray.sort(function(a, b) {
  if (a is less than b by some ordering criterion)
     return -1;
  if (a is greater than b by the ordering criterion)
     return 1;
  // a must be equal to b
  return 0;
});

EDIT: It looks like you have a single-element array with an object as the element. Objects are unordered. You have to transform it to an array before it can be sorted. Try this (with the Object.keys and Array.prototype.map functions added via augment.js for older browsers):

var result = Object.keys(myArray[0]).sort().map(function(key) {
    return [key,myArray[0][key]];
});

This will give you a sorted, nested array of the form:

[["Brand Name","threadless"],
 ["Function Category","T-Shirt"],
 ...
]
like image 34
Roy Tinker Avatar answered Sep 19 '22 14:09

Roy Tinker