JuliaIO / JSON.jl

JSON parsing and printing
Other
311 stars 100 forks source link

question: JSON.json(array) #93

Open EricForgy opened 9 years ago

EricForgy commented 9 years ago

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.

StefanKarpinski commented 9 years ago

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

EricForgy commented 9 years ago

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.

josefsachsconning commented 8 years ago

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

TotalVerb commented 7 years ago

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.

yig commented 4 years ago

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.