JSON

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.

Compilation

Clone the GitHub repository, create the Makefile using CMake, and build the library with make. You can force a specific Fortran compiler, if needed:

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

This will create the static library libjsonfortran.a, the shared library libjsonfortran.so, and some *.mod files for linking.

Reading a JSON file

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

{
  "t0": 0.0,
  "dt": 1.0,
  "tf": 86400.0,
  "mu": 398600.4418,
  "x0": [
    10000.0,
    10000.0,
    10000.0,
    1.0,
    2.0,
    3.0
  ]
}

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. Use get() to access primitive and structured types:

! json.f90
program main
    use :: json_module
    implicit none
    integer, parameter         :: dp = selected_real_kind(15, 307)
    real(kind=dp)              :: t0, dt, tf, mu
    real(kind=dp), allocatable :: x0(:)
    type(json_file)            :: json
    logical                    :: is_found

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

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

    ! Read in the data.
    call json%get('t0', t0, is_found); if (.not. is_found) stop
    call json%get('dt', dt, is_found); if (.not. is_found) stop
    call json%get('tf', tf, is_found); if (.not. is_found) stop
    call json%get('mu', mu, is_found); if (.not. is_found) stop
    call json%get('x0', x0, is_found); if (.not. is_found) stop

    ! Output values.
    print *, t0
    print *, dt
    print *, tf
    print *, mu
    print *, x0

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

To read JSON data from a string, call the method load_from_string() instead.

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

$ gfortran7 -Wl,-rpath=/usr/local/lib/gcc7/ -I./include/ -L./lib/ \
  -o json json.f90 ./lib/libjsonfortran.a
$ ./json