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)

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?


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) 

or with:

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

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


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


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"


Thanks, I am using pretty printing now.