TOML
TOML.jl is a Julia standard library for parsing and writing TOML v1.0 files.
Parsing TOML data
julia> using TOMLjulia> data = """[database]server = "192.168.1.1"ports = [ 8001, 8001, 8002 ]""";julia> TOML.parse(data)Dict{String, Any} with 1 entry:"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:
julia> using TOMLjulia> TOML.parse("""value = 0.0.0""")ERROR: TOML Parser error:none:1:16 error: failed to parse valuevalue = 0.0.0^[...]
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:
julia> using TOMLjulia> err = TOML.tryparse("""value = 0.0.0""");julia> err.typeErrGenericValueError::ErrorType = 14julia> err.line1julia> err.column16
Exporting data to TOML file
The TOML.print function is used to print (or serialize) data into TOML
format.
julia> using TOMLjulia> data = Dict("names" => ["Julia", "Julio"],"age" => [10, 20],);julia> TOML.print(data)names = ["Julia", "Julio"]age = [10, 20]julia> fname = tempname();julia> open(fname, "w") do ioTOML.print(io, data)endjulia> TOML.parsefile(fname)Dict{String, Any} with 2 entries:"names" => ["Julia", "Julio"]"age" => [10, 20]
Keys can be sorted according to some value
julia> using TOMLjulia> TOML.print(Dict("abc" => 1,"ab" => 2,"abcd" => 3,); sorted=true, by=length)ab = 2abc = 1abcd = 3
For custom structs, pass a function that converts the struct to a supported type
julia> using TOMLjulia> struct MyStructa::Intb::Stringendjulia> TOML.print(Dict("foo" => MyStruct(5, "bar"))) do xx isa MyStruct && return [x.a, x.b]error("unhandled type $(typeof(x))")endfoo = [5, "bar"]
References
TOML.parseTOML.parsefileTOML.tryparseTOML.tryparsefileTOML.printTOML.ParserTOML.ParserError
