Json parsing with iRules
Everyone should have written a JSON parser once in his life, here is mine.
JSON is now the format of choice for most APIs. It's time we were able to parse JSON with F5 iRules too, as simple string matching is not always good enough. That's why I wrote a simple JSON parser for iRules. It is a validating single pass parser that processes the JSON string char by char until the JsonPath expression matches, no recursion or any other fancy stuff. As I do not wanted to reinvent the wheel, it is basically a rewrite of the JSON parser found in the mongoose webserver project in plain TCL.
The usage is very simple:
set token [call json::json_get_tok { $json $path }]
- $json is the json string to parse
- $path is a JsonPath expression, following operators are implemented:
Operator | Description |
$ | The root element to query. This starts all path expressions. |
.<name> | Dot-notated child. |
[<number>] | Array index. |
Example
Simple JSON:
{
"aud": "audience \"test\"",
"iss": "https://issuer.de/issuer/",
"iat": 1701422123,
"roles": [
"role1",
"role2"
],
"obj": {
"sub": "adcad2b8",
},
"ver": "2.0"
}
JsonPath expression to parse this simple JSON:
JsonPath | Return value |
$.aud |
"audience \"test\"" |
$.iat |
1701422123 |
$.obj.sub |
"adcad2b8" |
$.roles[0] |
"role1" |
To decode the extracted JSON string:
set decoded [call json::json_decode_str { $token }]
This removes the enclosing quotes from a string and decodes JSON escapes.
Code
You can find the code and further documentation in my GitHub repository: https://github.com/JuergenMang/f5-irules-json
- PeteWhiteEmployee
haven't used it yet but i'm sure i will do in the future. Very useful.