jacobwilliams / json-fortran

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

What is the difference? #435

Closed nyckmaia closed 5 years ago

nyckmaia commented 5 years ago

I have a C++ application that call a Fortran subroutine (using ISO_C_BINDING) passing a const C char* that contains the JSON file full path as input argument. It works well, like this pseudo-code below:

! Main JSON file
type(json_file) :: project

! subroutine input argument:
character(kind=C_CHAR), target, intent(in) :: project_path(*)

! Will be used to convert C String to Fortran String:
character(kind=C_CHAR, len=:), pointer :: prj_path

! Convert C char array to Fortran string:
call C_F_STRPOINTER (project_path, prj_path, 80)

! initialize the class
call project%initialize()

! read the file:
call project%load_file(filename = prj_path)

call project%update('date_time', date_time, found)
if ( .not. found ) stop 1

call project%print_file(prj_path)

In this example you can see that I use the update method to create a new date_time JSON field in my file. This field date_time really not exist in the current file. It is created at run-time. Ok!

So, this loaded JSON object has a JSON field called settings_path, that stores another JSON file path.

I can get the settings_path value using the get method, but when I create another JSON object using the settings_path string and tried to add new fields inside of it, my Fortran code crash!

Here is my example:

! Another JSON file
type(json_file) :: settings

call project%get('job(1).settings_path', settings_path, found)  
if ( .not. found ) stop 1

! NO ERRORS: I got the "settings path" string ok!

call settings%initialize()

call settings%load_file(filename = settings_path)
call settings%update('version', 1, found)
if ( .not. found ) stop 1
! STOPS HERE!

Trying a lot of things, I discovery that, if I open this "settings" JSON file and I create the field version manually, the Fortran update/change the value without errors. But I would like to Fortran creates the new JSON field version at run-time, like my first example above.

Why the first goes Ok, and the second crashs?

jacobwilliams commented 5 years ago

I think update only works if the variable is already there. Have you tried add?

nyckmaia commented 5 years ago

Thanks @jacobwilliams ... Yes...today I change my Fortran source-code to use the add method intead of update method. Now, add works as really "adding" a new field AND... if the field already exists, the add method works like a update method....replacing the old value by the new one.

So, I'm thinking that I can use only the add method...for "adding" and "update" JSON fields/values.

I don't understand why yesterday the update method was working like "adding" new fields too. But, today, the update method only "updates" a existent JSON field and the add method "adds" and "updates" JSON fields.

Thank you for your help!