Nice programing

Chrome 및 Opera가 색인 ASC로 JSON 개체를 정렬하는 것을 어떻게 중지합니까?

nicepro 2020. 12. 1. 19:47
반응형

Chrome 및 Opera가 색인 ASC로 JSON 개체를 정렬하는 것을 어떻게 중지합니까?


문제가 있습니다.

ajax를 사용하여 다음을 사용하여 올바르게 구성된 JSON 객체를 보냈습니다.

            $.ajax({
                type: "POST", 
                url: SITE_URL+'/data.php',
                dataType: "json",
                data: { ajax: 1 },
                success: function(data) {
                    console.log(data);
                }
            });

그러나 Opera와 Chrome은 동일한 개체를 수신했지만 잘못된 순서로 개체를 인쇄하지만 둘 다 그대로 두지 않고 ID 번호로 정렬하는 것처럼 보입니다!

이 자동 정렬을 중지하는 방법이 있습니까?

편집, 그것이 인덱스 번호로 정렬된다는 것을 알게 된 후 가장 좋은 방법은 object_id를 저장하는 데 인덱스를 사용하지 않고 대신 객체를 주문하려는 ID 번호를 저장하는 것입니다.

그러나 나는 여전히 정렬을 중지하는 방법이 있는지 알고 싶습니다.

감사합니다

Edit2, 저는이 방법으로 객체를 남용하는 것처럼 느끼기 때문에 다른 방법으로 작업 할 것임을 주목하고 싶습니다. 그러나 Opera와 Chrome이 내 개체 ID의 순서를 변경하는 것이 자신의 권리라고 생각하는 이유를 여전히 이해하고 싶습니다.

문제는 제가 처리 능력을 절약하려는 것입니다. ID를 가진 사람이 있다고 가정 해 보겠습니다.

1. John, 2.Frank 및 3.Sally. 그러나이 사람들은 각각 hight 속성 집합 (및 기타 사항)을 가지고 있습니다. 1. 존 180, 2. 프랭크 220, 3. 샐리 150. 처리 비용을 절약하기 위해 사람들의 결과를 높이별로 정렬하여 다른 속성과 함께 2, 1, 3 배열을 얻도록 요청합니다. 이 배열을 JSON으로 만들어 브라우저로 보냅니다.

이제 FF는 새로운 순서를 유지합니다. People [1]은 여전히 ​​John이지만 For n as person 루프에서는 순서가 맞지 않습니다.

이 문제를 해결할 수 없다면 SQL 단계에서 정렬을 귀찮게하지 않고 JS 단계에서 추가 루프 및 정렬을 추가해야하지만 이미 Js가 무겁기 때문에 브라우저에 더 많은 스트레스를주지 않으려 고했습니다. 페이지.

많은 감사


같은 문제가 있었고 dmc의 솔루션을 따랐지만 int 값 앞에 공백을 추가하여 문자열로 만들었습니다.

숫자가 아닌 다른 문자 대신 공백을 사용하는 이점은 이후에 POST 된 값을 다시 제거하지 않고도 mySQL 검색 절에서 직접 사용할 수 있다는 것입니다.


다른 브라우저는 다른 방식으로 객체를 처리합니다. 내 잘못은 내가 객체를 만든 순서를 참조로 사용하지 말아야하는 부분을 사용하는 것입니다.


정수를 문자열로 변경해도 작동하지 않았습니다 (Chrome, jQuery 1.7.1). 따라서 명령을 유지하기 위해 (예, 객체 남용) 다음과 같이 변경했습니다.

optionValues0 = {"4321": "option 1", "1234": "option 2"};

이에

optionValues0 = {"1": {id: "4321", value: "option 1"}, "2": {id: "1234", value: "option 2"}};

JSON이 객체가 아니라 배열이 아니라면 특정 순서로 있어야한다는 표준이 없습니다. 그러나 이것은 데이터를 얻기 위해 객체를 반복 할 필요가 없기 때문에 문제가되지 않아야합니다. 간단히 속성을 참조 할 수 있습니다.


일부 브라우저는 int 인 키를 정렬합니다. 반면에 문자열로 변경하고 나중에 되 돌리는 것이 매우 쉽습니다. 내 솔루션은 키에 "i"를 추가하는 것이 었습니다. 각 브라우저에서 완벽하게 작동합니다. :) 도움이되기를 바랍니다. :)


나는 동일한 "문제"를 가지고 있었고 돌아가서 코드를 너무 많이 변경하고 싶지 않았습니다. 적어도 Google 크롬은 숫자 색인 만 다시 정렬한다는 것을 알아 냈습니다. 인덱스가 문자열로 간주되는 한 "의도 된"순서로 표시됩니다. 누군가 Opera에서 이것을 확인할 수 있습니까?


저에게 맞는 솔루션이 없습니다 (2017 년 8 월). 문자열을 사용하더라도 Chrome과 Safari (다른 브라우저를 테스트하지 않음)는 여전히 문자열을 기준으로 정렬되었습니다. 대신 내가 한 것은 정수 키를 값 문자열과 연결하는 것입니다. 예 :

result[string_value + str(integer_key)] = string_value

이렇게하면 문자열이 먼저 표시되고 브라우저는 자유롭게 정렬 할 수 있습니다. 그런 다음 몇 가지 간단한 논리를 사용하여 키와 값을 분리했습니다.

도움이 되었기를 바랍니다.


가장 좋은 방법은 연관 배열을 전혀 피하는 것 같습니다. 연관 배열을 보내려면 키 중 하나와 값 중 하나 인 두 개의 개별 배열로 보내면됩니다. 이를 수행하는 PHP 코드는 다음과 같습니다.

    $arWrapper = array();
    $arWrapper['k'] = array_keys($arChoices);
    $arWrapper['v'] = array_values($arChoices);
    $json = json_encode($arWrapper);

원하는 모든 작업을 수행 할 수있는 간단한 JavaScript 코드

            for (i=0; i < data['k'].length; i++) {
                console.log('key:' + data['k'][i] + ' val:' + data['v'][i]);
            }

비슷한 문제가 있었고 jQuery에 게시했습니다 . $ .getJSON이 Chrome / IE에서 데이터를 정렬합니까?


이 코드를 사용하여이 문제를 해결했습니다.

$('.edit_district').editable("/moderator/sale/edit_sale/", {
    data   : " {'_7':'10 street', '_9':'9 street', '_11':'park'}",
    type   : 'select',
    submit    : 'OK',
    onblur : 'submit'
});

그리고 script.php에서 :

...
case "id_district":

$district = Districts::GetDistrictByID(Database::getInstance(), (int)substr($value,1));

if($district instanceof District){
    $data["id_district"] = $district->id_district;
    echo $district->title;
}

break;

...

You need to trick Google Chrome (and others) into thinking you have a string and not a number. Changing the JSON to {"2423":'abc', "2555":'xyz'} will not work.

I had to use "_2423" and "_2555" as indexes in my object to get it to work.

Further, debugging the output to console.log or using for x in y gave different results as to _.each method (see the underscore framework).

You can see my test/proof in JSFiddle with "_" vs no prefix and the for x in y loop: http://jsfiddle.net/3f9jugtg/1/


Make your object identifier in the JSON string parameter, it works without automatic sorting.


There are some cases where you will need to use the record id to group things in a post process loop. Putting quotes around the key value will work. Or you can use array_merge on the final array which resets the keys.

$processed_array = array(
  235=>array("id"=>235,"name"=>"Something"),
  27=>array("id"=>27,"name"=>"Something")
);

array_merge($processed_array);

A print_r($processed_array); now returns the following:

$processed_array = array(
  0=>array("id"=>235,"name"=>"Something"),
  1=>array("id"=>27,"name"=>"Something")
);

I had the same issue and took me a while to work out what was even causing it, what a pain. I ended up removing ID from the index and used array_push, instead of being:

$section[$s_id]['Type'] = $booktype;

etc. I changed it to

array_push($sections, array('ID'=>$s_id, 
                            'CourseID'=>$courseid, 
                            'SectionName'=>$secname, 
                            'Order'=>$order, 
                            'Created'=>$created, 
                            'Description'=>$desc
                            ));

Which allowed me to keep the ordering from PHP since the new indexs where already in order (0,1,2,3 etc as opposed to 112, 56, 411 etc)


I had the same issue with chrome, so frustrating. I send it a certain way, why can't chrome just take my word for it? I get that there's no "standard" way, but if that's the case, why impose your own order??

Anyway, I handled it by turning my objects into arrays, so that

{ 0: "", 2: "Frame", 1: "Masonry" }

became

[[ 0, "" ], [ 2, "Frame" ], [ 1, "Masonry" ]]

Had to change some javascript, but it ended up working perfectly.


One trick that can help is as follow:

You have to add "i" to key while you prepare your data in for loop, that made a trick. Works perfectly for each browsers.

for Example :

 for(var i=1;i<4;i++){

 data[''+i+''+your_random_generatedId+'']  = {"questionText":"","answer":"","options":"",noOfOptions:""};

 console.log(data[''+i+''+your_random_generatedId+'']); // This prints the log of each object inside data 

 }

 console.log(data); // This will print the Object without sorting

Hence your Object will be as follow:

Object {156674: Object, 201705: Object, 329709: Object}

hope this helps :)


When you pass the data object to console.log, JavaScript will end up calling the toString() method for the data object. Since you don't like the default format of data's toString() method, you'll have to do the work yourself.

You can dump the object's fields yourself if you want that type of control - you'd have to get the keys/fields and sort them and then build the string version yourself.

something like:

for (field in obj)
    add field to array

sort array into whatever order you want

for (field in array)
    get value of field from obj
    create string of field : value, append to main string

console.log(main string)

참고URL : https://stackoverflow.com/questions/5020699/how-do-you-stop-chrome-and-opera-sorting-json-objects-by-index-asc

반응형