Forum Discussion

NoamRotter's avatar
NoamRotter
Icon for Altostratus rankAltostratus
Apr 26, 2020
Solved

Extract value from json

Hi, I have a webapp which accepts a POST with JSON payload. the JSON has only one key:value I need to write to log the value of the key. For example: This is the payload of the JSON: {      ...
  • PeteWhite's avatar
    Apr 29, 2020

    Great! HTTP::payload must be able to retrieve it because it comes in a single packet so it doesn't need to accumulate. Note that if the payload was larger ( eg 1K ) then this might fail and you'd have to use HTTP::collect.

    We can use regexp in multiple ways to retrieve the substring. Try this:

    when HTTP_REQUEST {
      if { [HTTP::method] == "POST"} {
        log local0. ">>> Method is POST<<<"
        if {  [ regexp -- {"token": "(.+)"} [HTTP::payload] a b ] } {
            log local0.debug "Token Found a:$a b:$b"
        }
      }
    }

    $a should be the whole of the line, $b should be only the token part.

    Take a look here for more detail on how to use regexp:

    PS the other way we could have done it is this:

    set token [lindex [ regexp -inline -- {"token": "(.+)"} [HTTP::payload] ] 1]