JSON对象被Javascript重新排序 [英] JSON object being reordered by Javascript

查看:46
本文介绍了JSON对象被Javascript重新排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过PHP生成的相当大的JSON对象.它从数据库中创建一个PHP对象,其键为整数,即1-100.这些键不是按顺序排列的,而是按随机顺序排列的,例如55、72、5、8、14、32、64等.然后,我使用json_encode将对象输出为JSON.然后,我使用AJAX调用来获取该JSON并将其存储在变量中.但是,该变量的JSON对象的顺序为1-100,而不是上面的排序顺序.

I have a rather large JSON object being generated via PHP. It creates a PHP object out of a database, with keys that are integers, ie 1-100. These keys are not in that order though, they are in a random order, such as 55, 72, 5, 8, 14, 32, 64, etc. I then use json_encode to output the object as JSON. I then use an AJAX call to grab that JSON and store it in a variable. However, that variable has the JSON object in order 1-100, instead of the sorted order above.

有什么想法为什么要这样做以及如何解决?

Any ideas why it's doing that, and how I can fix it?

推荐答案

对象中的键在技术上没有排序.您期望它们以特定顺序排列是数据结构中的错误.JSON解析器会将数字键解释为数组位置.

Keys within an object aren't technically ordered. That you expect them to be in a particular order is a mistake in data structure. A JSON parser will interpret numerical keys as array positions.

这个

{
    55: "foo",
    29: "bar",
    ...
}

在语义上与以下内容相同:

is semantically the same as:

object[55] = "foo"
object[29] = "bar"

这是:

[
    ...
    "bar" //index 29
    ...
    "foo" //index 55
    ...
]

相反,您应该将对象的顺序和标识分开:

Instead, you should separate the order and the identify of your objects:

[
    {id: 55, content: "foo"},
    {id: 29, content: "bar"},
    ...
]

这篇关于JSON对象被Javascript重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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