ten
ten

Reputation: 817

Ways of taking care of JSON with Matrix data on Julia

I am in a Julia project and I am trying to write code for saving Matrix data as .json file. The problem I am facing is when I read the json string from the file and parse it, the Matrix is changed into "vector of vectors".

In [1]:
n=10
mat = zeros(n,n)
data = Dict(
    "n" => n,
    "mat" => mat
)
using JSON
output_text = JSON.json(data)
out = open("jsonTest.json","w")
println(out,output_text)
close(out)


In [2]:
data


Out[2]:
Dict{String, Any} with 2 entries:
  "mat" => [0.0 0.0 … 0.0 0.0; 0.0 0.0 … 0.0 0.0; … ; 0.0 0.0 … 0.0 0.0; 0.0 0.…
  "n"   => 10


In [3]:
op = JSON.parsefile("jsonTest.json")


Out[3]:
Dict{String, Any} with 2 entries:
  "mat" => Any[Any[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], Any[0.0, …
  "n"   => 10

According to this question, one simple solution is using hcat function to re-convert "vector of vectors" to "matrix" when reading the json.

It works, but it is a bit messy(and might time-consuming) to take care of each matrix in the json. Is there simpler way?

Any information would be appreciated.

Upvotes: 1

Views: 1117

Answers (1)

jling
jling

Reputation: 2301

Since JSON (the spec) does not know about Matrix, you need to either do nested vectors (as you're right now), or reshape.

I personally prefer reshape because its memory layout is the same as an concrete Matrix in Julia and reshap has no allocation and less overhead over hcat

julia> a = rand(2,3)
2×3 Matrix{Float64}:
 0.534246  0.282277  0.140581
 0.841056  0.443697  0.427142

julia> as = JSON3.write(a)
"[0.5342463881378705,0.8410557102859995,0.2822771326129221,0.44369703601566,0.1405805564055571,0.4271417199755423]"

julia> reshape(JSON3.read(as), (2,3))
2×3 reshape(::JSON3.Array{Float64, Base.CodeUnits{UInt8, String}, Vector{UInt64}}, 2, 3) with eltype Float64:
 0.534246  0.282277  0.140581
 0.841056  0.443697  0.427142

Upvotes: 4

Related Questions