1

I have a PHP file that scrapes an external URL for certain classes, then puts them into an array. I have then encoded the array using json_encode(). The array is in the order it must be iterated, but for some reason the JSON doesn't iterate in the correct order. It's in descending order, instead of ascending order.

Here is an example of the JSON returned:

[{
   "id":1,
   "info":
         {
            "title":"Design Prepaid cards with HD quality ",
            "titleurl":"http:\/\/www.peopleperhour.com\/job\/design-prepaid-ards-with-hd-quality-380258",
            "price":"\u00a3 400 ",
            "urgent":"Urgent",
             "jobID":"380258"
         }
 },
 {
    "id":2,
    "info":
         {
             "title":"Charted accontant",
             "titleurl":"http:\/\/www.peopleperhour.com\/job\/charted-accontant-380251",
             "price":"\u00a3 60 ",
             "urgent":"Urgent",
             "jobID":"380251"
         }
 }]

This is how I am currently displaying the JSON:

    var jsonResults = JSON.parse(data);

    var count = (jsonResults.length);
    // Iterate Through Results
    $.each(jsonResults, function(key, value)
    {

        // Display Data
        $('#resultsPanel').fadeIn('slow');

        $('#resultsPanel').prepend(
            '<div class="item" id="'+ value.info.jobID +'">'+
            '<div class="title"><a href="'+ value.info.titleurl+'" target="_blank">'+ value.info.title +'</a></div>'+
            '<div class="price">'+ value.info.price +'</div>'+
            '</div>'
        );
    });

Is it possible to order the JSON?

MikeF
  • 485
  • 6
  • 22
  • You can sort arrays, if you're trying to have a certain order in the containing array, but objects can't be ordered, as order is not guaranteed in objects. – adeneo Dec 10 '13 at 21:57
  • As a sidenote, just replacing the each loop with `for(var i=jsonResult; i--;)` { will iterate the array backwards – adeneo Dec 10 '13 at 22:00
  • I am assuming it's in the same order as the array in the JSON object? – Captain John Dec 10 '13 at 22:01
  • A side note, `.fadeIn` should be _after_ all the data has been inserted, shouldn't it? – Izkata Dec 10 '13 at 22:04
  • @Izkata - doesn't really matter as prepending is pretty fast, and fading is async, but placing it inside the loop seems like a bad idea, so yes, the fadeIn should be placed after the each loop, and of course, using append would solve the issue with wrong order. – adeneo Dec 10 '13 at 22:09
  • @Izkata - Yes, it should be _after_. It's still in development, so bugs are present. @CaptainJohn - Yes, if I visit the .php page that scrapes/sets up the array, it outputs it in the exact format that I require it parsing. @adeneo `for(var i=jsonResult; i--;){` How would I then call the individual keys/values? – MikeF Dec 10 '13 at 22:10

3 Answers3

4

See this part:

$('#resultsPanel').prepend(

"prepend" means "put at the beginning", which is going to reverse your list (put item 1 at the beginning, then put item 2 at the beginning, etc...). I'm pretty sure you meant:

$('#resultsPanel').append(
Izkata
  • 8,961
  • 2
  • 40
  • 50
  • You sir, are a genius! Something as simple as that! However, that does bring one more issue to the table. The whole point of this script is to update automatically using a `setInterval` function which triggers the `.ajax` call after a specified interval time. However, if any new jobs have been posted, they will then end up at the bottom of the container, not the top. – MikeF Dec 10 '13 at 22:14
  • @MikeF If you don't want to change the javascript, and just keep `prepend`, PaparazzoKid's suggestion of reversing the initial data might work. I'd prefer separating the initial load from the update, though. – Izkata Dec 10 '13 at 22:46
1

Objects are un-ordered sets. You can't specify an order on them in a cross-browser compliant manner. There is no concept of original order unless it's already ordered by a rule.

So sort the data on the server and then enumerate over it in the same sorted order.

EDIT

As I mentioned below, my jQuery knowledge is minimal, but maybe something like this could work:

var jsonResults = JSON.parse(data);
Object.keys(jsonResults).reverse().forEach(function (key, value) {
    // do something here
});
TheCarver
  • 19,391
  • 25
  • 99
  • 149
  • 1
    @Izkata - JSON is data format used in strings, what's important is the data structure once that string is parsed into javascript objects, is it an array or is it an object, there's no such thing as "list", and only arrays can be exepected to have order. – adeneo Dec 10 '13 at 22:02
  • That's exactly what I'm doing. The data is scraped and placed into an array with a unique identifying key/value pair. It is then encoded using the `json_encode` function. If I go to the PHP file where the data is generated, it outputs the JSON in the format/order that I require. Yet when it gets to client-side, it somehow gets ordered in reverse. – MikeF Dec 10 '13 at 22:02
  • @MikeF I'm not overly competent in jQuery but after having a quick browse, could you not use something like: `$(yourobject).toArray().reverse();` – TheCarver Dec 10 '13 at 22:06
  • @adeneo I'm doing a lot of Python nowadays and have come to say "list" for any sequential data structure in languages that don't have both as different things (like Perl). My point still stands: This data is an array of objects - it has order. – Izkata Dec 10 '13 at 22:06
0

There is another question similar to this that might give you the answer: sort json object in javascript

Community
  • 1
  • 1
Stig Husby
  • 1,677
  • 12
  • 15