Compatibility with JSON
Contents
Compatibility with JSON#
The Jonquil project provides a flavor of TOML Fortran which can handle JSON. It is available from the `toml-f/jonquil <https://github.com/toml-f/jonquil`__ repository and can be included using the same steps as shown for TOML Fortran in Using TOML Fortran.
Tip
All types and procedures in TOML Fortran and Jonquil are fully compatible. Everything that is possible with TOML Fortran can be done with Jonquil, they can be mixed and matched without restriction. In short, Jonquil is TOML Fortran.
Using Jonquil#
You can follow all recipes and tutorials in this documentation using Jonquil by just replacing the tomlf module with the jonquil module. All derived types, procedure names and interfaces use the json_ prefix instead of toml_, with the exception of the toml_table type which becomes a json_object.
The following example program shows how to load JSON data from a string and access the value using the build interface.
program demo
use jonquil, only : json_loads, json_value, json_object, json_error, cast_to_object, &
& get_value
implicit none
class(json_value), allocatable :: val
type(json_object), pointer :: object
type(json_error), allocatable :: error
integer :: ival
call json_loads(val, '{"a":1,"b":2}', error=error)
if (allocated(error)) then
print '(a)', error%message
stop
end if
object => cast_to_object(val)
if (associated(object)) then
call get_value(object, "a", ival)
print '(a,1x,i0)', "a is", ival
call get_value(object, "b", ival)
print '(a,1x,i0)', "b is", ival
end if
In contrast to TOML Fortran the loaded data structure is always returned as a polymorphic value, which can be dispatched by using a select type construct or by obtaining a pointer using cast_to_object / cast_to_array as appropriate.
Jonquil promises seamless compatibility with TOML Fortran, the data structure we just loaded can be manipulated with any procedure from the tomlf module and vice versa.
block
use tomlf, only : toml_table, toml_array, add_array, set_value, toml_serialize
integer :: it
type(toml_table), pointer :: table
type(toml_array), pointer :: array
! Add an array to the object
call add_array(object, "c", array)
call set_value(array, [-1, 0, 1])
! Create a new subobject / subtable
call get_value(object, "d", table, requested=.true.)
call set_value(table, "sub", "table")
print '(a)', "# representation in TOML land"
print '(a)', toml_serialize(object)
end block
Since the json_object is just a flavor of the toml_table type, it can be used in the same way as any other table.