JSON + Fortran

Introducing json-fortran, an easy-to-use JSON API written in modern Fortran.  As far as I know, it’s currently the only publically-available production-ready JSON API for Fortran that does not involve an interface to C libraries.  The code is hosted at GitHub, and is released under a BSD-style license.

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.

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 6-element 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,

The code would look something like this:

program propagate

use json_module

implicit none

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

!load the file:
call config%load_file('config.json')

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

! ...

end program propagate

Of course, real production code would have more graceful error checking. For example, to make sure the file was properly parsed and that each variable was really present.  These features are included in the API, including helpful error messages if something goes wrong.

Posted in Programming Tagged with: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *