Skip to content
Jacob Williams edited this page Feb 13, 2017 · 11 revisions

json-fortran is a JSON API written in modern Fortran.

Why Use It?

According to the JSON standard (ECMA-404):

JSON is a lightweight, text-based, language-independent data interchange format. It was derived from the ECMAScript programming language, but is programming language independent. JSON defines a small set of structuring rules for the portable representation of structured data.

Fortran users may find JSON quite useful as a configuration file format. Typically, large and complicated Fortran codes (say, in the fields of climate modeling or trajectory optimization) require data to be read from configuration files. JSON has many advantages over a roll-your-own file format, or a Fortran namelist, namely:

  • It's a standard.
  • It's human-readable and human-editable.
  • API's exist for many other programming languages.

Example

Consider the example of a program to propagate a spacecraft state vector. The required information is the initial time t0, step size dt, final time tf, central body gravitational parameter mu, and the state vector x0. The JSON configuration file might look something like this:

{
    "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
    ]
}

The code would look something like this (note that a real production code would likely have more graceful error checking):

program propagate

use json_module

implicit none

real(wp) :: t0, dt, tf, mu
real(wp),dimension(:),allocatable :: x0
type(json_file) :: config
logical :: found

!initialize the class:
call config%initialize()

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

!read in the data:
call config%get('t0',t0,found); if (.not. found) stop
call config%get('dt',dt,found); if (.not. found) stop
call config%get('tf',tf,found); if (.not. found) stop
call config%get('mu',mu,found); if (.not. found) stop
call config%get('x0',x0,found); if (.not. found) stop

!propagate:
! ...

!cleanup:
call config%destroy()

end program propagate

More information