JavaScript Object Notation (JSON) is a lightweight data-interchange format derived from the object literals of ECMAScript and defined in RFC 7159. The format can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays).

JSON is often used to store and exchange data across networks and programming languages. The module json-fortran provides a thread-safe and object-oriented API for reading and writing JSON files in Fortran 2008.


Clone the GitHub repository, create the Makefile using CMake, and build the library with Make. If required, you can force a specific Fortran compiler with -DCMAKE_Fortran_COMPILER and -DCMAKE_INSTALL_RPATH:

$ git clone https://github.com/jacobwilliams/json-fortran
$ cd json-fortran/
$ mkdir build && cd build/
$ cmake -DCMAKE_Fortran_COMPILER=gfortran12 -DCMAKE_INSTALL_RPATH=/usr/local/lib/gcc12/ ..
$ make

This will create the static library libjsonfortran.a, the shared library libjsonfortran.so, and the module files for linking. The Fortran Package Manager is supported as well:

$ fpm build --profile=release


Given is a JSON file config.json with the following contents:

  "t0": 0.0,
  "dt": 1.0,
  "tf": 86400.0,
  "mu": 398600.4418,
  "x0": [

In order to read the file, one has to import the module json_module, initialise an object of class json_file, and call the method load_file() with the file path as an argument. Call the method load_from_string() to read JSON data from a string instead. Use the method get() to access primitive and structured types, for example:

! example.f90
program example
    use :: json_module, rk => json_rk
    implicit none

    real(kind=rk)              :: t0, dt, tf, mu
    real(kind=rk), allocatable :: x0(:)
    type(json_file)            :: json
    logical                    :: is_found

    ! Initialise the json_file object.
    call json%initialize()

    ! Load the file.
    call json%load_file('config.json'); if (json%failed()) stop

    ! Read in the data.
    json_block: block
        call json%get('t0', t0, is_found); if (.not. is_found) exit json_block
        call json%get('dt', dt, is_found); if (.not. is_found) exit json_block
        call json%get('tf', tf, is_found); if (.not. is_found) exit json_block
        call json%get('mu', mu, is_found); if (.not. is_found) exit json_block
        call json%get('x0', x0, is_found); if (.not. is_found) exit json_block
    end block json_block

    ! Output values.
    if (is_found) then
        print *, t0, dt, tf, mu
        print *, x0
    end if

    ! Clean up.
    call json%destroy()
end program example

Copy the static library libjsonfortran.a to ./lib/ and the module files to ./include/ inside your workspace directory. You can then compile and run the example with:

$ gfortran12 -I./include/ -o example example.f90 ./lib/libjsonfortran.a
$ ./example

Fortran Libraries