TOML

TOML.jl is a Julia standard library for parsing and writing TOML v1.0 files.

Parsing TOML data

  1. julia> using TOML
  2. julia> data = """
  3. [database]
  4. server = "192.168.1.1"
  5. ports = [ 8001, 8001, 8002 ]
  6. """;
  7. julia> TOML.parse(data)
  8. Dict{String, Any} with 1 entry:
  9. "database" => Dict{String, Any}("server"=>"192.168.1.1", "ports"=>[8001, 8001

To parse a file, use TOML.parsefile. If the file has a syntax error, an exception is thrown:

  1. julia> using TOML
  2. julia> TOML.parse("""
  3. value = 0.0.0
  4. """)
  5. ERROR: TOML Parser error:
  6. none:1:16 error: failed to parse value
  7. value = 0.0.0
  8. ^
  9. [...]

There are other versions of the parse functions (TOML.tryparse and [TOML.tryparsefile]) that instead of throwing exceptions on parser error returns a TOML.ParserError with information:

  1. julia> using TOML
  2. julia> err = TOML.tryparse("""
  3. value = 0.0.0
  4. """);
  5. julia> err.type
  6. ErrGenericValueError::ErrorType = 14
  7. julia> err.line
  8. 1
  9. julia> err.column
  10. 16

Exporting data to TOML file

The TOML.print function is used to print (or serialize) data into TOML format.

  1. julia> using TOML
  2. julia> data = Dict(
  3. "names" => ["Julia", "Julio"],
  4. "age" => [10, 20],
  5. );
  6. julia> TOML.print(data)
  7. names = ["Julia", "Julio"]
  8. age = [10, 20]
  9. julia> fname = tempname();
  10. julia> open(fname, "w") do io
  11. TOML.print(io, data)
  12. end
  13. julia> TOML.parsefile(fname)
  14. Dict{String, Any} with 2 entries:
  15. "names" => ["Julia", "Julio"]
  16. "age" => [10, 20]

Keys can be sorted according to some value

  1. julia> using TOML
  2. julia> TOML.print(Dict(
  3. "abc" => 1,
  4. "ab" => 2,
  5. "abcd" => 3,
  6. ); sorted=true, by=length)
  7. ab = 2
  8. abc = 1
  9. abcd = 3

For custom structs, pass a function that converts the struct to a supported type

  1. julia> using TOML
  2. julia> struct MyStruct
  3. a::Int
  4. b::String
  5. end
  6. julia> TOML.print(Dict("foo" => MyStruct(5, "bar"))) do x
  7. x isa MyStruct && return [x.a, x.b]
  8. error("unhandled type $(typeof(x))")
  9. end
  10. foo = [5, "bar"]

References

  1. TOML.parse
  2. TOML.parsefile
  3. TOML.tryparse
  4. TOML.tryparsefile
  5. TOML.print
  6. TOML.Parser
  7. TOML.ParserError