Converting nested vectors of Any

Hello there,

I have parsed json from a file. According to the language that made the data, it contains a “collection” of matrices of 64-bit floats. But it is being read in as a format involving Any:

julia> raw = JSON.parsefile(path)
julia> typeof(raw)
Dict{String, Any}
julia> typeof(raw["0"])
Vector{Any} (alias for Array{Any, 1})
julia> typeof(raw["0"][1])
Vector{Any} (alias for Array{Any, 1})
julia> typeof(raw["1"][1][1])
Float64
julia> size(raw)
100
julia> size(raw["1"])
96
julia> size(raw["1"][1])
3

Now I want to convert this to a 3 dimensional array that is indexed in the same way. The problem is that the only way that I have found to do it requires 12 or so lines of code. So there has to be some built-in function or functions that just casts this It is the right format (?) :

raw = JSON.parsefile(path)

m = length(raw)
n = length(raw["1"])
l = length(raw["1"][1])

v::Array{Float64,3} = Array{Float64}(undef, m, n, l)

for (i,(key,value)) in enumerate(raw)
    for (j, vec) in enumerate(value)
        v[i,j,:] = Float64.( vec )
    end
end

So my question is: How can I do this efficiently in a couple of lines instead of a dozen?

You can use hcat()

raw = JSON.parsefile(path)

m = length(raw)
n = length(raw["1"])
l = length(raw["1"][1])

result = zeros(Float64, (l, n, m))

for (i, (key, value)) in enumerate(raw)
    result[:, :, i] .= hcat([cat(Float64, vec...) for vec in value]...)
end

For each key-value pair, it converts the Vector{Any} to a matrix of Float64 values using a list comprehension that applies the cat function to each vector in the collection and then concatenates them horizontally using hcat . The resulting matrix is then assigned to the corresponding slice of the 3-dimensional array.