Inserts element
after p
, and updates the JSON structure accordingly.
program test
use json_module
implicit none
logical(json_LK) :: found
type(json_core) :: json
type(json_value),pointer :: p,new,element
call json%load(file='myfile.json', p=p)
call json%get(p,'x(3)',element,found) ! get pointer to an array element in the file
call json%create_integer(new,1,'') ! create a new element
call json%insert_after(element,new) ! insert new element after x(3)
call json%print(p,'myfile2.json') ! write it to a file
call json%destroy(p) ! cleanup
end program test
element
are carried along. p
[1] - [2] - [3] - [4]
|
[5] - [6] - [7] n=3 elements inserted
element last
Result is:
[1] - [2] - [5] - [6] - [7] - [3] - [4]
Type | Intent | Optional | Attributes | Name | ||
---|---|---|---|---|---|---|
class(json_core), | intent(inout) | :: | json | |||
type(json_value), | pointer | :: | p |
a value from a JSON structure (presumably, this is a child of an object or array). |
||
type(json_value), | pointer | :: | element |
the element to insert after |
subroutine json_value_insert_after(json,p,element) implicit none class(json_core),intent(inout) :: json type(json_value),pointer :: p !! a value from a JSON structure !! (presumably, this is a child of !! an object or array). type(json_value),pointer :: element !! the element to insert after `p` type(json_value),pointer :: parent !! the parent of `p` type(json_value),pointer :: next !! temp pointer for traversing structure type(json_value),pointer :: last !! the last of the items being inserted integer :: n !! number of items being inserted if (.not. json%exception_thrown) then parent => p%parent ! set first parent of inserted list: element%parent => parent ! Count the number of inserted elements. ! and set their parents. n = 1 ! initialize counter next => element%next last => element do if (.not. associated(next)) exit n = n + 1 next%parent => parent last => next next => next%next end do if (associated(parent)) then ! update parent's child counter: parent%n_children = parent%n_children + n ! if p is last of parents children then ! also have to update parent tail pointer: if (associated(parent%tail,p)) then parent%tail => last end if end if if (associated(element%previous)) then ! element is apparently part of an existing list, ! so have to update that as well. if (associated(element%previous%parent)) then element%previous%parent%n_children = & element%previous%parent%n_children - n element%previous%parent%tail => & element%previous ! now the last one in the list else ! this would be a memory leak if the previous entries ! are not otherwise being pointed too ! [throw an error in this case???] end if !remove element from the other list: element%previous%next => null() end if element%previous => p if (associated(p%next)) then ! if there are any in the list after p: last%next => p%next last%next%previous => element else last%next => null() end if p%next => element end if end subroutine json_value_insert_after