jQuery的getJSON不保持原始顺序

时间:2015-08-07 00:52:04

标签: jquery json

拥有以下文件(customers.json):

{"3":"Andy", "1":"Bruce", "4":"Charlie", "2":"David"}

使用此代码:

jQuery.getJSON("/Customers.json", function (data) {
    console.log(data);
});

这将输出以下内容:

{"1":"Bruce", "2":"David", "3":"Andy", "4":"Charlie"}

我的Json按名称按字母顺序排列,但这段代码似乎按数字顺序排列。这是一个功能吗?我该如何阻止这种情况发生?

是否有所作为,我使用的是Firefox 39.0

修改

这里真正的问题是,无论如何要做到这一点,保留所有数据,并维持收到的顺序?

5 个答案:

答案 0 :(得分:2)

你的Json应该是什么样的

[{"id":"3", "name":"Andy"}, {"id":"1", "name":"Bruce"}, {"id":"4", "name":"Charlie"}, {"id":"2", "name":"David"}]

您发送的是一系列对象(客户),因此您的数据结构应理想地反映出来。并将其作为数组传输,您可以保留订单,如上所述。

答案 1 :(得分:0)

如果您关心订单,则必须在响应JSON中提交一个列表

 ["Andy", "Bruce", "Charlie","David"]

然后:

 $.each(data,function(i,v){
      console.log(v)
      // or
      console.log(data[i])
 })

答案 2 :(得分:0)

当通过线路传输的字符串转换为Javascript对象(表示JSON数据的对象)时,您最终得到的是一个具有属性和值的任何其他对象。对象中没有属性排序。

从JSON创建的对象:

{"3":"Andy", "1":"Bruce", "4":"Charlie", "2":"David"}

与使用此Javascript创建的对象相同:

obj = {}; // <-- Not an array!
obj[1] = 'Andy';
obj[2] = 'Bruce';
obj[3] = 'Charlie';
obj[4] = 'David';

如果要按属性的顺序输出对象,则需要先将值加载到数组中,然后按字母顺序对数组进行排序。

类似的东西:

var sorted = [];
for (var prop in data) {
    if (data.hasOwnProperty(prop)) {
        sorted(json[prop]);
    }
}
sorted.sort();
console.log(sorted);

答案 3 :(得分:0)

  

无论如何要做到这一点,保留所有数据,并保持   为了

尝试使用$.map()Array.prototype.sort()返回值数组,返回对象的属性

var json = {
  "3": "Andy",
  "1": "Bruce",
  "4": "Charlie",
  "2": "David"
};
var res = $.map(json, function(val, key) {
  // keep all data, maintain order
  // return array having value as string with comma ","
  // as separator between `val` from object `key` from object
  // `val`: `Andy` , `key`: `3`
  return [ val + ", " + key ]
}).sort();
console.log(res);
document.body.textContent = res;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

答案 4 :(得分:0)

Is this a feature?

Yes kind of, the order of properties of object can be up to an implementation. Some browsers do maintain the order, some not. This is what ES5 Specification says:

The mechanics and order of enumerating the properties (step 6.a in the first algorithm, step 7.a in the second) is not specified.

So, as soon as you get an JavaScript object from JSON literal the order of the properties can be lost.

And how do I stop this from happening?

Is there any way to do this, keeping ALL the data, and maintaining the order in which is received?

The only real way to solve the issue is to specify the order of objects explicitly.