处理稀疏数组的 JSON 实现

发布于 2024-08-28 19:44:47 字数 254 浏览 17 评论 0原文

我需要知道是否有任何 JSON 实现可以让我满意地处理稀疏数组。我看到了这个问题:如何在 JSON 中表示稀疏数组? 但使用对象而不是数组对我来说不是一个选择;我需要一个数组。

我的最低要求是实现填补“未定义”的任何空白。否则,我会在 JSON 编码之前编写防御性代码来填补空白。

I need to know if any JSON implementations can handle sparse arrays to my satisfaction. I've seen the question: How to represent a sparse array in JSON? but using an object rather than an array is not an option for me; I need an array.

My minimum requirement would be that the implementation fill in any gaps with "undefined". Otherwise I am writing defensive code that fills in the gaps myself, before JSON encoding.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

欢你一世 2024-09-04 19:44:47

不可能。忘记实现吧,规范中显然不允许这样做。

http://json.org/

数组仅按值定义。对象适用于索引/键有意义的情况。

Not possible. Forget implementations, it's just plain not allowed in the spec.

http://json.org/

Arrays are defined by value only. Objects are for when the index/key has meaning.

十级心震 2024-09-04 19:44:47

您是否可以使用一个对象,其中属性名称是索引,属性值是值,然后通过中间函数运行它来创建稀疏数组?

function getSparseArray(obj) {
  var ary = [];
  for (prop in obj) {
    var i = parseInt(prop,10);
    if (!isNaN(i)) {
      ary[i] = obj[prop];
    }
  }
  return ary;
}

您可以发送类似的内容

{ "5":"Five", "11":"Eleven", "99":"Ninety-Nine"}

,然后返回一个仅填充三个值的数组:

ary[5] = "Five"
ary[11] = "Eleven"
ary[99] = "Ninety-Nine"
ary[0] = 'undefined'
ary[98] = 'undefined'
etc.

ary 这里的长度为 100,但从您的意义上来说,它将是一个“稀疏”数组。

Could you use an object where the property name was an index and the property value was the value, then run it through an intermediary function to create your sparse array?

function getSparseArray(obj) {
  var ary = [];
  for (prop in obj) {
    var i = parseInt(prop,10);
    if (!isNaN(i)) {
      ary[i] = obj[prop];
    }
  }
  return ary;
}

You would send it something like

{ "5":"Five", "11":"Eleven", "99":"Ninety-Nine"}

and get back an array that was populated with just three values:

ary[5] = "Five"
ary[11] = "Eleven"
ary[99] = "Ninety-Nine"
ary[0] = 'undefined'
ary[98] = 'undefined'
etc.

ary here would have a length of 100, but it would be a "sparse" array in your sense.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文