jacobwilliams / json-fortran

A Modern Fortran JSON API
https://jacobwilliams.github.io/json-fortran/
Other
332 stars 83 forks source link

How to get a derived-type table? #523

Closed GHNewbiee closed 1 year ago

GHNewbiee commented 1 year ago

Hi. The structure of the .json file is:

{
  "table": [
    ["string1", 1.0],
    ["string2", 2.0],
    ["string3", 3.0],
  ]
}

The derived types are:

module derived_types
  use kind_params, only: sp
  implicit none
  public

  type :: str_t
    character(len=:), allocatable :: str
  end type

  type :: row_t
    type(str_t) :: former
    real(sp)    :: latter
  end type

  type :: elem_t
    type(row_t) :: elem(1)
  end type

  type :: array_t
    type(elem_t), allocatable :: array(:)
  end type

end module derived_types

and the main file is:

program test
  use derived_types
  use json_module
  implicit none

  character(len=:), allocatable :: path
  type(json_file)               :: file
  type(elem_t), allocatable     :: data(:)
  logical                       :: found

  call file%initialize()              !< initialize the class
  call file%load(filename = path)     !< read the file
  call file%get('table', data, found) !< retrive the data
end program test

I have tried call file%get('table', data, found) but unfortunately failed with the following error.

  xxx |             call file%get('table', data, found)
      |                     1
Error: Found no matching specific binding for the call to the GENERIC ‘get’ at (1)

Any advice/suggestion? Tia

GHNewbiee commented 1 year ago

For the time being, I use string array ie


{
  "table": [
    "string1, 1.0",
    "string2, 2.0",
    "string3, 3.0",
  ]
}
jacobwilliams commented 1 year ago

You'd have to write code specific to your types, to populate the variables yourself. JSON-Fortran doesn't know anything about how to populate a custom user type (indeed, it's not possible to write such a library in Fortran).