extract_json_int Subroutine

subroutine extract_json_int(line, key, value)

Extract an integer value from a JSON key-value pair.

Arguments

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

Source line and key token to find

character(len=*), intent(in) :: key

Source line and key token to find

integer, intent(out) :: value

Extracted integer value


Source Code

  subroutine extract_json_int(line, key, value)
    !! Extract an integer value from a JSON key-value pair.
    implicit none

    ! Arguments
    character(*), intent(in) :: line, key
    !! Source line and key token to find
    integer, intent(out) :: value
    !! Extracted integer value

    ! Local variables
    integer :: pos, pos2, stat
    !! Temporary indices and read status
    character(64) :: numstr
    !! Numeric substring buffer

    value = 0
    pos = index(line, trim(key))
    if(pos .eq. 0) return

    pos = pos + len_trim(key)
    pos2 = index(line(pos:), ':')
    if(pos2 .eq. 0) return
    pos = pos + pos2

    numstr = adjustl(line(pos:))
    if(numstr(1:1) .eq. '"')then
       numstr = numstr(2:)
       pos2 = index(numstr, '"')
       if(pos2 .gt. 0) numstr = numstr(1:pos2-1)
    end if
    pos2 = index(numstr, ',')
    if(pos2 .gt. 0) numstr = numstr(1:pos2-1)

    read(numstr, *, iostat=stat) value

  end subroutine extract_json_int