0

I’m playing around with json objects in javascript and wanted see if someone could help me out with a problem

My json file contains a list of hash objects containing a key (id) and the value being an array of [ ipaddress, timestamp, url]

e.g.

{"output":
    {
    "1":["10.0.0.1","2012-07-11T11:41:42+01:00","http://myurl.com"],
    "2":["10.0.0.1","2012-07-11T11:45:42+01:00","http://myurl2.com"],
    "3":["192.168.1.1","2012-07-11T11:41:47+01:00","http://myurl3.com"]
    }
}

What I want to do is be able to sort on the contents of the arrays

For example I’d like to go through the json and pull out the highest timestamp for each ip address

So an example output for the json above would look like:-

10.0.0.1 - http://myurl2.com
192.168.1.1 - http://myurl3.com

At the moment I have a simple function to output the raw data in a div, but I’m sure I could handle the arrays better

  var displayOutput = function(data){
    var container = $("#fragment-1");
   var body = “”;
    $.each(data.output, function(key, val) {
      var arr = val.toString().split(",");
      body = body + arr[0]+ ' - ' +  arr[1]) + ' - ' +  arr[2]
    });
    container.html(body);                                                
  };
user891380
  • 227
  • 6
  • 17
  • You have to convert your data into another structure which is sortable. For example an object with IPs as properties, each value being an array of timestamps (which then can be sorted). – Felix Kling Jul 25 '12 at 13:38

2 Answers2

0

You will need to change the format as JSON arent to easy to sort.

Maybe a multi dimensional array?

Maybe this might help: Sorting an array of JavaScript objects

Or this: http://www.devcurry.com/2010/05/sorting-json-array.html

Or this: Sorting a JSON object in Javascript

One of these will definitely lead to to a good solution. Need any help ask :)

Community
  • 1
  • 1
Lemex
  • 3,772
  • 14
  • 53
  • 87
  • Your answer is a bit confusing. It does not make sense to talk about "sorting JSON is not easy" because JSON is a data format, just like XML. – Felix Kling Jul 25 '12 at 13:50
  • I wouldnt recommend it, al though i provided links which explain how to do it with examples – Lemex Jul 25 '12 at 13:53
  • thanks all, in the end I converted the json to a multidimensional array and went from there – user891380 Jul 26 '12 at 07:32
0

You can Use underscore.js library. For example, you can sort collection with:

_.sortBy(yourData.output, function (elem) {
    return new Date(elem[1]).getTime() - new Date().getTime();
});

Of course you need to parse JSON to JavaScript object first.