parse_json_int_array_from_strings Subroutine

subroutine parse_json_int_array_from_strings(line, values)

Parse a JSON array of string-encoded integers.

Arguments

Type IntentOptional Attributes Name
character(len=*), intent(in) :: line

Source line containing a JSON array

integer, intent(inout), allocatable :: values(:)

Parsed integer values


Source Code

  subroutine parse_json_int_array_from_strings(line, values)
    !! Parse a JSON array of string-encoded integers.
    implicit none

    ! Arguments
    character(*), intent(in) :: line
    !! Source line containing a JSON array
    integer, allocatable, intent(inout) :: values(:)
    !! Parsed integer values

    ! Local variables
    integer :: pos, pos2, pos3, stat, ival
    !! Temporary indices, read status and parsed integer value
    character(64) :: numstr
    !! Numeric token buffer

    if(allocated(values)) deallocate(values)
    allocate(values(0))

    pos = index(line, '[')
    if(pos .eq. 0) return
    pos = pos + 1

    do
       pos2 = index(line(pos:), '"')
       if(pos2 .eq. 0) exit
       pos = pos + pos2
       pos3 = index(line(pos:), '"')
       if(pos3 .eq. 0) exit
       numstr = line(pos:pos+pos3-2)
       read(numstr, *, iostat=stat) ival
       if(stat .eq. 0) values = [values, ival]
       pos = pos + pos3
       if(index(line(pos:), ']') .gt. 0 .and. &
            (index(line(pos:), '"') .eq. 0 .or. &
                 index(line(pos:), ']') .lt. index(line(pos:), '"'))) exit
    end do

  end subroutine parse_json_int_array_from_strings