从 Javascript 解析 JSON 时如何保持顺序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10034655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:31:24  来源:igfitidea点击:

How to maintain order when parsing JSON from Javascript?

javascriptjson

提问by TehWan

The data I am sending my page is encoded in JSON, parsed using Javascript then displayed in an HTML SELECT element using a loop. The data arrives already sorted, but I am having issues keeping the correct order when decoding the JSON string, which nullifies the sorting applied on the data.

我发送给我的页面的数据以 JSON 编码,使用 Javascript 解析,然后使用循环显示在 HTML SELECT 元素中。数据到达时已经排序,但我在解码 JSON 字符串时遇到了保持正确顺序的问题,这会使应用于数据的排序无效。

Sample data: {"test":{"4":"first","5":"second","3":"third"}}

样本数据: {"test":{"4":"first","5":"second","3":"third"}}

Using jQuery's JSON parser and Javascript's eval() function, I am getting the following results:

使用 jQuery 的 JSON 解析器和 Javascript 的 eval() 函数,我得到以下结果:

{"test":{"3":"third","4":"first","5":"second"}}

{"test":{"3":"third","4":"first","5":"second"}}

It is not possible to modify the format of the data and the keys ("4", "5", "3") must remain in the same order. The real data is much more complex, but this sample illustrates very well my issue.

无法修改数据的格式,并且键(“4”、“5”、“3”)必须保持相同的顺序。实际数据要复杂得多,但此示例很好地说明了我的问题。

How can I maintain the order of the JSON data when parsing it from Javascript?

从 Javascript 解析 JSON 数据时如何维护它的顺序?

采纳答案by CD..

Use an array if you want to keep the order. That should be the only way to maintain the order in javascript.

如果您想保持顺序,请使用数组。这应该是在 javascript 中维护订单的唯一方法。