0

I sort my data in the sql query and then json_encode the data. It gives me something like that.

{
  "9535": {
    "id_contrat": "9535",
    "statut_contrat": "A",
    "etat_contrat": "B",
    "num_publication": "1299-6793"
  },
  "1621723": {
    "id_contrat": "1621723",
    "statut_contrat": "N",
    "etat_contrat": "A",
    "num_publication": "1299-6793"
  }
}

The problem is when I use $.parseJSON, it sort me the data like this.

9535: {id_contrat: "9535", statut_contrat: "A", etat_contrat: "B", num_publication: "1299-6793"}
1621723: {id_contrat: "1621723", statut_contrat: "N", etat_contrat: "A", num_publication: "1299-6793"}

I want to keep the same order before my $.parseJSON because im building an select option with the data value and the first option has to be the 1621723 and not 9535 because im using controles on the first element of the option.

My current function :

function setContractField(msg)
{
    var option = '';
    var idContrat;
    var statutContrat;
    var etatContrat;
    var numPublication;
    console.log(msg);
    console.log($.parseJSON(msg));
    $.each($.parseJSON(msg), function(index,value) {
        $.each(value, function(key, value) {
            if(key == 'id_contrat') {
                idContrat = value;
            }
            if(key == 'statut_contrat') {
                statutContrat = value;
            }
            if(key == 'etat_contrat') {
                etatContrat = value;
            }
            if(key == 'num_publication') {
                numPublication = value;
            }

        });
        option += '<option status="'+ statutContrat + '" etat="'+ etatContrat + '" value="'+ idContrat + '">' + idContrat + '</option>';
    });
    return option;
}

I saw on the internet that i have to build an array with the parseJson result but I don't understand how.

The two object has to be ordered by alphabetic on the etat_contrat field.

phuzi
  • 12,078
  • 3
  • 26
  • 50
  • Can you give an example where it **does** sort it? Your "parsed" data is in the same order as the "unsorted" data. – freedomn-m Nov 05 '19 at 15:23
  • Possible duplicate: https://stackoverflow.com/questions/28166518/parsejson-sorts-my-json-data – freedomn-m Nov 05 '19 at 15:27
  • Possible solution: don't use integers for your keys, eg prefix with `id` id9535 id1621723 then it won't sort them – freedomn-m Nov 05 '19 at 15:28
  • The problem is that i cant use an static prefix because the id are dynamics – Nicolas Boulein Nov 05 '19 at 15:37
  • Your structure is in a dictionary (Enclosed by `{}`). Dictionaries don't maintain order. If you want to be able to maintain a specific order, then you need to use an array (enclosed by `[]`). – Robert McKee Nov 05 '19 at 15:43

0 Answers0