Error writing down a JSON file with JSON.jl

Hello,
I’m trying to export some data to a JSON format, the file is succesfully created with this function:

function writeJSON()
    r = rand(3,3)
    N=3
    data = [Dict("x"=> r[i,1],"y"=> r[i,2],"z"=>r[i,3]) for i=1:N]
   
    open("foo.json","w") do f
       JSON.print(f, data, 4)
    end
    
end

but in the resulting foo.json the “y” and “z” values are inverted, i’m not sure why, it should look like this:
image

And the file generated is this:

[
    {
        "x": 0.8212211605554455,
        "z": 0.5338611788222072,
        "y": -0.20146475424383917
    },
    {
        "x": -0.5412324524725539,
        "z": 0.4710378620065893,
        "y": 0.696556361644057
    },
    {
        "x": -0.5595207932869602,
        "z": -0.2356000256849917,
        "y": 0.7946251378963304
    }, .....

How can i fix it?

That has nothing to do with JSON, Dicts are unordered:

julia> Dict("x"=> r[1,1],"y"=> r[2,2],"z"=>r[3,3])
Dict{String, Float64} with 3 entries:
  "x" => 0.993151
  "z" => 0.0282255
  "y" => 0.29912

If you need to rely on the order use an OrderedDict from OrderedCollections or another structure which preserves order.

1 Like