带小数点的JSON键不按顺序排列

Has*_*sen 0 javascript ajax jquery json

我在JSON文件中有密钥,并且在使用密钥处理时不按数字顺序排列.有任何解决这个问题的方法吗?

$.getJSON("file.json", function(thedata) {
  var items = [];
  $.each(thedata, function(key, val) {
    items.push(key);
  });
Run Code Online (Sandbox Code Playgroud)

JSON文件:

"3.5":"some data",
"8":"some data",
"13":"some data",
"17.5":"some data",
"18":"some data",
Run Code Online (Sandbox Code Playgroud)

它们的密钥将按此顺序通过: 8, 13, 18, 3.5, 17.5

T.J*_*der 5

JSON对象属性没有顺序,因此通过反序列化JSON创建的对象可以按任何顺序具有属性.*

您可以获取密钥,对它们进行排序,然后遍历这些属性:

$.getJSON("file.json", function(thedata) {
  var items = [];
  Object.keys(thedata)
    .sort(function(left, right) { return left - right; })
    .forEach(function(key) {
      var val = thedata[key];
      // Use `key`, `val`...
    });
});
Run Code Online (Sandbox Code Playgroud)

没有$.getJSON部分的实时拷贝:

var json =
    '{"3.5":"some data",' +
    '"8":"some data",' +
    '"13":"some data",' +
    '"17.5":"some data",' +
    '"18":"some data"' +
    '}';
var thedata = JSON.parse(json);
var items = [];
Object.keys(thedata)
  .sort(function(left, right) { return left - right; })
  .forEach(function(key) {
    var val = thedata[key];
    console.log(key + " = " + val);
  });
Run Code Online (Sandbox Code Playgroud)

或者,按顺序将数据作为数组数组返回:

[
    ["3.5", "some data"],
    ["8", "some data"],
    ["13", "some data"],
    ["17.5", "some data"],
    ["18", "some data"]
]
Run Code Online (Sandbox Code Playgroud)

然后:

$.getJSON("file.json", function(thedata) {
    thedata.forEach(function(entry) {
        var key = entry[0], val = entry[1];
        // Use `key`, `val` here
    });
});
Run Code Online (Sandbox Code Playgroud)

实例(没有$.getJSON):

var json =
    '[' +
        '["3.5", "some data"],' +
        '["8", "some data"],' +
        '["13", "some data"],' +
        '["17.5", "some data"],' +
        '["18", "some data"]' +
    ']';
var thedata = JSON.parse(json);
thedata.forEach(function(entry) {
    var key = entry[0], val = entry[1];
    console.log(key + " = " + val);
});
Run Code Online (Sandbox Code Playgroud)

如果您可以使用ES2015 +功能(您只支持尖端浏览器,或者您需要转换),您可以使用解构分配forEach:

const json =
    '[' +
        '["3.5", "some data"],' +
        '["8", "some data"],' +
        '["13", "some data"],' +
        '["17.5", "some data"],' +
        '["18", "some data"]' +
    ']';
const thedata = JSON.parse(json);
thedata.forEach(([key, val]) => {
    console.log(key + " = " + val);
});
Run Code Online (Sandbox Code Playgroud)


*从ES2015开始,JavaScript对象属性确实有一个订单,至少对于某些操作而言,但依赖该订单通常并不常见.