ParseJSON对我的json数据进行排序 [英] ParseJSON sorts my json data

查看:531
本文介绍了ParseJSON对我的json数据进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的ajax调用,如下所示:

I have a simple ajax call that looks like this:

var data = jQuery.parseJSON(response.d);

response.d的内容是:

{"d":"[[{\"ExtensionData\":{},\"categoryId\":\"Help\"}],{\"11\":\"This is 11\",\"10\":\"This is 10\",\"7\":\"This is 7\",\"6\":\"This is 6\",\"12\":\"This is 12\",\"5\":\"This is 5\",\"4\":\"This is 4\",\"2\":\"This is 2\",\"1\":\"This is 1\"}]"}

当我运行代码并查看其中包含的数据时,它看起来像这样:

When I run the code and look at what data contains, it looks like this:

  1. 这是1"
  2. 这是2"
  3. 这是3"
  4. 这是4"
  5. 这是5"
  6. 这是6"

...等等,您就明白了.为什么突然将其排序?如何关闭自动排序"?

... and so on, you get the idea. Why is it sorted all of the sudden? How do I turn off the "autosort"?

推荐答案

从不保证在JavaScript的反序列化和序列化之间保留对象键顺序.保证键顺序的唯一方法是提取对象的键并根据确定性标准对它们进行排序,即,为了保证顺序,必须使用数组.

Retaining object key order between unserialisation and serialisation in JavaScript is never guaranteed. The only way to guarantee key order is to extract an object's keys and sort them according to a deterministic criteria, i.e. in order to guarantee order, you must use an array.

可能的解决方案是在服务器响应的键值集合(原始对象)之外还包含对象键数组( ).通过遍历有序键,可以按所需顺序访问对象.

A possible solution to your problem would be to include an array of the object keys in addition to your key-value collection (the original object) to your server response. By iterating over the ordered keys, you can access the object in the order you want.

例如

var data = { 
    values: { /* your original object here */ },
    /* keep a record of key order and include the keys as an array 
       in your response. That way you can guarantee order. */
    keys: [11, 10, 7, 6, 12, 5, 4, 2, 1]
};

data.keys.forEach(function (key) {
   var value = data.values[key];

   /* do work here */
});

这篇关于ParseJSON对我的json数据进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆