jacobwilliams / json-fortran

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

Generate `json` string #576

Closed fedebenelli closed 2 weeks ago

fedebenelli commented 1 month ago

Hi! Thanks for developing this library!

I need a very specific usage where I generate a json string from some input data. Just to provide a simple example of what I want to do json_str would be an arbitrary dimension:

   function parameters_to_char(a, b, c) result(json_str)
      use json_module, only: json_core, json_value
      real(rk) :: a, b, c
      character(len=500) :: json_str

      type(json_core) :: json
      type(json_value),pointer :: p

      call json%initialize()
      call json%create_object(p,'')

      call json%add(p, "a", a)
      call json%add(p, "b", b)
      call json%add(p, "c", c)

      ! Write to string instead of to a file
      call json%print(p, json_str)

      !  json_str would be the resulting JSON string
   end function

This usage is because I send later that string to a C library that does its own thing. While I could write to a tmp file and read it later as a character I would prefer being able to directly obtain the string (since it might be called thousands of times).

I read through the documentation but I couldn't find any way to do this, just writing to files or printing to console. Is it possible?

An override of write could be a good extension for a pull request?

write (*, *) json
fedebenelli commented 1 month ago

I see in the source code that there is the subroutine json_value_to_string(json,p,str) subroutine. Where str is an allocatable string. For some reason the generic print won't use this and always takes the json_value_to_filename instead :thinking: (even when I convert to allocatable the json_str variable)

fedebenelli commented 1 month ago

Calling call json%print_to_string(p, json_str) seems to do the trick! I'm keeping this issue for now to know if what I was doing was bad practice or truly an error

jacobwilliams commented 2 weeks ago

Yes, serialize (or print_to_string) is what you need here. The print ones aren't overloaded with print_to_string because there would be no way to disambiguate it from print_to_filename.