将多维数组正确转换为JSON(并返回)

时间:2023-01-21 21:28:33

Is there a standard way of translating multi-dimensional arrays to JSON and back? Does this depend on the language and the relationship between byte ordering and rows/columns/pages etc.? I am working working in Matlab. In Matlab, an array of integers, with values of say 1 through 10, with a shape of 5 x 2, would have the following 2-D layout:

是否有一种将多维数组转换为JSON并返回的标准方法?这取决于语言和字节顺序与行/列/页面等之间的关系吗?我在Matlab工作。在Matlab中,一个整数数组,其值为1到10,形状为5 x 2,将具有以下2-D布局:

1 6
2 7
3 8
4 9
5 10

1 6 2 7 3 8 4 9 5 10

as opposed to:

而不是:

1 2
3 4
5 6
7 8
9 10

1 2 3 4 5 6 7 8 9 10

The question is, if I translate the 2-D array into a JSON string, should I get:
[[1,2,3,4,5],[6,7,8,9,10]]
or
[[1,6],[2,7],[3,8],[4,9],[5,10]]

问题是,如果我将2-D数组转换为JSON字符串,我应该得到:[[1,2,3,4,5],[6,7,8,9,10]]或[[1 1,6],[2,7],[3,8],[4,9],[5,10]

My preference would be the first case, since it is sequential in terms of memory access.

我的偏好是第一种情况,因为它在内存访问方面是顺序的。

So the explicit question then is, which way are n-d arrays written?

那么明确的问题是,编写n-d数组的方式是什么?

  1. By memory - innermost should be sequential in memory
  2. 通过内存 - 内部应该在内存中顺序
  3. high to low dimensions - innermost is lowest dimension (which in this case matches the memory for Matlab)
  4. 从高到低的维度 - 最里面是最低维度(在这种情况下匹配Matlab的内存)
  5. low to high dimensions - innermost is highest dimension
  6. 从低到高的尺寸 - 最里面是最高尺寸

1 个解决方案

#1


0  

If you say you have a 5x2 array, in JS you probably mean you have an array of length of 5, each element of which is an array of length 2. So the "layout" you get is:

如果你说你有一个5x2数组,在JS中你可能意味着你有一个长度为5的数组,每个元素都是一个长度为2的数组。所以你得到的“布局”是:

[ [a00, a01],
  [a10, a11],
  [a20, a21],
  [a30, a31],
  [a40, a41] ]

Decoding that in terms of 1..10 is entirely up to you.

根据1..10进行解码完全取决于您。

an array of integers, with values of say 1 through 10, with a shape of 5 x 2

一个整数数组,其值为1到10,形状为5 x 2

There is no single correct way to put values 1..10 into an array 5x2. So [[1,6],[2,7],[3,8],[4,9],[5,10]] would be just as good as [[1,2],[3,4],[5,6],[7,8],[9,10]].

将值1..10放入数组5x2没有一种正确的方法。所以[[1,6],[2,7],[3,8],[4,9],[5,10]]和[[1,2],[3,4]一样好,[5,6],[7,8],[9,10]。

#1


0  

If you say you have a 5x2 array, in JS you probably mean you have an array of length of 5, each element of which is an array of length 2. So the "layout" you get is:

如果你说你有一个5x2数组,在JS中你可能意味着你有一个长度为5的数组,每个元素都是一个长度为2的数组。所以你得到的“布局”是:

[ [a00, a01],
  [a10, a11],
  [a20, a21],
  [a30, a31],
  [a40, a41] ]

Decoding that in terms of 1..10 is entirely up to you.

根据1..10进行解码完全取决于您。

an array of integers, with values of say 1 through 10, with a shape of 5 x 2

一个整数数组,其值为1到10,形状为5 x 2

There is no single correct way to put values 1..10 into an array 5x2. So [[1,6],[2,7],[3,8],[4,9],[5,10]] would be just as good as [[1,2],[3,4],[5,6],[7,8],[9,10]].

将值1..10放入数组5x2没有一种正确的方法。所以[[1,6],[2,7],[3,8],[4,9],[5,10]]和[[1,2],[3,4]一样好,[5,6],[7,8],[9,10]。