JSON.jl icon indicating copy to clipboard operation
JSON.jl copied to clipboard

question: JSON.json(array)

Open EricForgy opened this issue 10 years ago • 5 comments

julia> a = [[1 2 3],[4 5 6]] 2x3 Array{Int64,2}: 1 2 3 4 5 6

julia> JSON.json(a) "[[1,4],[2,5],[3,6]]"

I would expect: "[[1,2,3],[4,5,6]]".

I'm running version 0.3.3.

EricForgy avatar Feb 14 '15 14:02 EricForgy

Julia is column major so a matrix is like a list of column vectors rather than a list of row vectors.

StefanKarpinski avatar Feb 14 '15 18:02 StefanKarpinski

Hi Stefan,

Thanks for the explanation. I had a hunch this was by design, which is why I put "question" in the subject. However, regardless of how Julia handles matrices internally, I think it still makes sense to use row major for JSON. While researching a bit, I found the following quote:

Note that even though R stores matrices in column major order, jsonlite encodes matrices in row major order. This is a more conventional and intuitive way to represent matrices and is consistent with the row-based encoding of data frames discussed in the next section. When the JSON string is properly indented (recall that white space and line breaks are optional in JSON), it looks very similar to the way R prints matrices:

[ [ 1, 4, 7, 10 ], [ 2, 5, 8, 11 ], [ 3, 6, 9, 12 ] ]

I also think encoding in row major is more intuitive and visually looks better when printed, but I can get used to this I suppose. For example,

 julia> b = [[1,4] [2,5] [3,6]]
2x3 Array{Int64,2}:
 1  2  3
 4  5  6

julia> JSON.json(b)
"[[1,4],[2,5],[3,6]]"

This doesn't look too bad... I guess :)

Then again, I can encode the transpose, but that doesn't feel right.

EDIT:

Here is another Matlab (column major) encoder that defaults to row major for JSON: JSONlab.

EricForgy avatar Feb 15 '15 08:02 EricForgy

I just encountered the same "problem". I am inclined to agree with Eric.

josefsachsconning avatar Jan 07 '16 16:01 josefsachsconning

How do Matlab and R serialize arrays with dimension three or greater? I'm worried that this change will introduce inconsistency with higher-order tensors.

TotalVerb avatar Oct 08 '16 05:10 TotalVerb

This is very surprising. I would have expected that if I accessed the first conceptual "row" data, regardless of internal storage, that I would get the same result. It's not as if the data has been flattened.

yig avatar Dec 04 '19 17:12 yig