How to write data to file with JSON.jl?

question
json

#1

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?


#2

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.


#3

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


#4

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"
}

#5

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