How to write data to file with JSON.jl?

Consider the following example:

using JSON

people = [Dict("name"=>"CoolGuy", "company"=>"tech") for i=1:1000]
companies = [Dict("name"=>"CoolTech", "address"=>"Bay Area") for i=1:100]

data = Dict("people"=>people, "companies"=>companies)
json_string = JSON.json(data)

open("foo.json","w") do f
  JSON.print(f, json_string)
end

This script generates a JSON file with a bunch of extra " marks, without space and newlines. How to print the output correctly, and preferably in a more readable format?

1 Like

You take data, transform it into a string (JSON formatted) and then transform this string into a quoted string when writing to a file. Instead, you should format only once, either with:

open("foo.json","w") do f 
    write(f, json_string) 
end

or with:

open("foo.json","w") do f
    JSON.print(f, data)
end

As for formatting, Iā€™d just use a browser extension (e.g. for Google Chrome) or editor mode to see the content formatted.

11 Likes

I was just typing this finding, thanks for the answer @dfdx :slight_smile:

1 Like

JSON supports pretty printing. Just pass a third argument with the number of spaces to indent by.

julia> JSON.print(STDOUT, Dict("julia" => "0.5"), 4)
{
    "julia": "0.5"
}
8 Likes

Thanks @fengyang.wang, I am using pretty printing now.

1 Like