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?

6
  • 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. Commented Dec 10, 2013 at 21:57
  • As a sidenote, just replacing the each loop with for(var i=jsonResult; i--;) { will iterate the array backwards Commented Dec 10, 2013 at 22:00
  • I am assuming it's in the same order as the array in the JSON object? Commented Dec 10, 2013 at 22:01
  • A side note, .fadeIn should be after all the data has been inserted, shouldn't it? Commented Dec 10, 2013 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. Commented Dec 10, 2013 at 22:09

3 Answers 3

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(
Sign up to request clarification or add additional context in comments.

2 Comments

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 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.
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
});

4 Comments

@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.
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 I'm not overly competent in jQuery but after having a quick browse, could you not use something like: $(yourobject).toArray().reverse();
@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.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.