Working with JSON data in iRules - Part 2
In part one, we covered JSON at a high level, got scripts working to pass JSON payload back and forth between client and server, and got the BIG-IP configured to manage this traffic. In this article, we'll start with an overview of the new JSON events, walk through an existing Tcl procedure that will print out the payload in log statements and explain the JSON:: iRules commands in play, and then we'll create a proc or two of our own to find keys in a JSON payload and log their values.
But before that, we're going to have a little iRules contest at this year's AppWorld 2026 in Vegas. Are you coming? REGISTER in the AppWorld mobile app for the contest (to be released soon)...seats are limited!
when CONTEST_SUBMISSION {
set name [string toupper [string replace Jason 1 1 ""]]
log local0. "Hey there...$name here."
log local0. "You might want to speak my language: structured, nested, and curly-braced."
}
Some details are being withheld until we gather at AppWorld for the contest, but there just might be a hint in that psuedo-iRule code above.
Crawl, Walk, Run!
Crawling
Let's start by crawling. With the new JSON profile, there are several new events:
- JSON_REQUEST
- JSON_REQUEST_MISSING
- JSON_REQUEST_ERROR
- JSON_RESPONSE
- JSON_RESPONSE_MISSING
- JSON_RESPONSE_ERROR
From there let's craft a basic iRule to see what triggers the events. Simple log statements in each.
when HTTP_REQUEST {
log local0. "HTTP request received: URI [HTTP::uri] from [IP::client_addr]"
}
when JSON_REQUEST {
log local0. "JSON Request detected successfully."
}
when JSON_REQUEST_MISSING {
log local0. "JSON Request missing."
}
when JSON_REQUEST_ERROR {
log local0. "Error processing JSON request. Rejecting request."
}
when JSON_RESPONSE {
log local0. "JSON response detected successfully."
}
when JSON_RESPONSE_MISSING {
log local0. "JSON Response missing."
}
when JSON_RESPONSE_ERROR {
log local0. "Error processing JSON response."
}
Now we need some client and server payload. Thankfully we have that covered with the script I shared in part one. We just need to unleash it! I have my Visual Studio Code IDE fired up with the F5 Extension and iRules editor marketplace extensions connected to my v21 BIG-IP, I have the iRule above loaded up in the center pane, and then I have the terminal on the right pane split three ways so I can a) generate traffic in the top terminal, b) view the server request/response in the middle terminal, and c) watch the logs from BIG-IP in the bottom terminal. Handy to have all that in one view in the IDE while working.
For the first pass, I'll send a request expected to work through the BIG-IP and get a response back from my test server. That command is:
./cspayload.py client --host 10.0.2.50 --port 80
And the result can be seen in the picture below (shown here to show the VS Code setup, I'll just show text going forward.)
You can see that the request triggered HTTP_REQUEST, JSON_REQUEST, and JSON_RESPONSE as expected.
Now, I'll send an empty payload to verify that JSON_REQUEST_MISSING will fire. The command for that is:
./cspayload1.py client --host 10.0.2.50 --port 80 --no-json
We get the event triggered as expected, but interestingly, the request is still processed and sent to the backend and the response is sent back just fine. (timestamps removed)
Rule /Common/irule.jsontest <HTTP_REQUEST>: HTTP request received: URI / from 10.0.2.95
Rule /Common/irule.jsontest <JSON_REQUEST_MISSING>: JSON Request missing.
Rule /Common/irule.jsontest <JSON_RESPONSE>: JSON response detected successfully.
My test script serverside code doesn't balk at an empty payload, but most services likely will, so you'll likely want to manage a reject or response as appropriate in this event.
Now let's trigger an error by sending some invalid JSON. The command I sent is:
./cspayload1.py client --host 10.0.2.50 --port 80 --malformed-custom '{invalid: "no quotes on key"}'
And that resulted in a successfully triggered JSON_REQUEST_ERROR and no payload was sent back to the backend server.
Rule /Common/irule.jsontest <HTTP_REQUEST>: HTTP request received: URI / from 10.0.2.95
Rule /Common/irule.jsontest <JSON_REQUEST_ERROR>: Error processing JSON request. Rejecting request.
Walking
After validating our events are triggering, let's take a look at the example iRule below that will use a procedure to print out the JSON payload.
when JSON_REQUEST {
set json_data [JSON::root]
call print $json_data
}
proc print { e } {
set t [JSON::type $e]
set v [JSON::get $e]
set p0 [string repeat " " [expr {2 * ([info level] - 1)}]]
set p [string repeat " " [expr {2 * [info level]}]]
switch $t {
array {
log local0. "$p0\["
set size [JSON::array size $v]
for {set i 0} {$i < $size} {incr i} {
set e2 [JSON::array get $v $i]
call print $e2
}
log local0. "$p0\]"
}
object {
log local0. "$p0{"
set keys [JSON::object keys $v]
foreach k $keys {
set e2 [JSON::object get $v $k]
log local0. "$p${k}:"
call print $e2
}
log local0. "$p0}"
}
string - literal {
set v2 [JSON::get $e $t]
log local0. "$p\"$v2\""
}
default {
set v2 [JSON::get $e $t]
if { $v2 eq "" && $t eq "null" } {
log local0. "${p}null"
} elseif { $v2 == 1 && $t eq "boolean" } {
log local0. "${p}true"
} elseif { $v2 == 0 && $t eq "boolean" } {
log local0. "${p}false"
} else {
log local0. "$p$v2"
}
}
}
}
If you build a lot of JSON utilities, I'd recommend creating an iRule that is just a library of procedures you can call from the iRule where your application-specific logic is. In this case, it's instructional so I'll keep the proc local to the iRule. Let's take this line by line.
- Lines 1-4 are the logic of the iRule. Upon the JSON_REQUEST event trigger, use the JSON::root command to load the JSON payload into the json_data variable, then pass that data to the print proc to, well, print it (via log statements.)
- Lines 5-47 detail the print procedure. It takes the variable e (for element) and acts on that throughout the proc.
- Lines 6-7 set the type and value of the element to the t and v variables respectively
- Lines 8-9 are calculating whitespace requirements for each element's value that will be printed
- Lines 10-38 are conditional logic controlled by the switch statement based on the element's type set by the JSON::type command, with lines 11-19 handling an array, lines 20-29 handling an object, lines 30-33 a string or literal, and lines 34-27 the default catchall.
- Lines 11 - 19 cover the JSON array, which in Tcl is a list. The JSON::array size command gets the list size and iterates through each list item in the for loop. The JSON::array get command then sets the value at that index in the loop to a second element variable (e2) and recursively calls the proc to start afresh on the e2 element.
- Lines 20-29 cover the JSON object, which in Tcl is a key/value dictionary. The JSON::object keys command gets the keys of the element and iterates through each key. The rest of this action is identical to the JSON array with the exception here of using the JSON::object get command.
- Lines 30-33 cover the string and literal types. Simple action here, uses the JSON::get command with the element and type and then logs it.
- For lines 34-43, this is the catch all for other types. Tcl represents a null type as an empty string, and the boolean values of true and false as 1 and 0 respectively. But since we're printing out the JSON values sent, it's nice to make sure they match, so I modified the function to print a literal null as a string for that type, and a literal true/false string for their 1/0 Tcl counterparts. Otherwise, it will print as is.
Ok, let's run the test and see what we see.
Clientside view:
./cspayload2.py client --host 10.0.2.50 --port 80
[Client] Connecting to http://10.0.2.50:80/
[Client] Sending JSON payload (POST):
{
"my_string": "Hello World",
"my_number": 42,
"my_boolean": true,
"my_null": null,
"my_array": [
1,
2,
3
],
"my_object": {
"nested_string": "I'm nested",
"nested_array": [
"a",
"b",
"c"
]
}
}
[Client] Received response (Status: 200):
{
"message": "Hello from server",
"type": "response",
"status": "success",
"data": {
"processed": true,
"timestamp": "2026-01-29"
}
}
Serverside view:
jrahm@udesktop:~/scripts$ ./cspayload2.py server --host 0.0.0.0 --port 8088
[Server] Starting HTTP server on 0.0.0.0:8088
[Server] Mode: Normal JSON responses
[Server] Press Ctrl+C to stop
[Server] Received JSON payload:
{
"my_string": "Hello World",
"my_number": 42,
"my_boolean": true,
"my_null": null,
"my_array": [
1,
2,
3
],
"my_object": {
"nested_string": "I'm nested",
"nested_array": [
"a",
"b",
"c"
]
}
}
[Server] Sent JSON response:
{
"message": "Hello from server",
"type": "response",
"status": "success",
"data": {
"processed": true,
"timestamp": "2026-01-29"
}
}
Resulting log statements on BIG-IP (with timestamp through rule name removed for visibility):
<JSON_REQUEST>: {
<JSON_REQUEST>: my_string:
<JSON_REQUEST>: "Hello World"
<JSON_REQUEST>: my_number:
<JSON_REQUEST>: 42
<JSON_REQUEST>: my_boolean:
<JSON_REQUEST>: true
<JSON_REQUEST>: my_null:
<JSON_REQUEST>: null
<JSON_REQUEST>: my_array:
<JSON_REQUEST>: [
<JSON_REQUEST>: 1
<JSON_REQUEST>: 2
<JSON_REQUEST>: 3
<JSON_REQUEST>: ]
<JSON_REQUEST>: my_object:
<JSON_REQUEST>: {
<JSON_REQUEST>: nested_string:
<JSON_REQUEST>: "I'm nested"
<JSON_REQUEST>: nested_array:
<JSON_REQUEST>: [
<JSON_REQUEST>: "a"
<JSON_REQUEST>: "b"
<JSON_REQUEST>: "c"
<JSON_REQUEST>: ]
<JSON_REQUEST>: }
<JSON_REQUEST>: }
The print procedure is shown here to include the whitespace necessary to prettify the output. Neat!
Running
Now that we've worked our way through the print function, let's do something useful! You might have a need to evaluate the value of a key somewhere in the JSON object and act on that. For this example, we're going to look for the nested_array key, retrieve it's value, and if an item value of b is found, reject the request by building a new JSON object to return status to the client.
First, we need to build a proc we'll name find_key that is similar to the print one above to recursively search the JSON payload. While learning my way through this, I also discovered I needed to create an additional proc we'll name stringify to, well, "stringify" the values of objects because they are still encoded.
stringify proc
proc stringify { json_element } {
set element_type [JSON::type $json_element]
set element_value [JSON::get $json_element]
set output ""
switch -- $element_type {
array {
append output "\["
set array_size [JSON::array size $element_value]
for {set index 0} {$index < $array_size} {incr index} {
set array_item [JSON::array get $element_value $index]
append output [call stringify $array_item]
if {$index < $array_size - 1} {
append output ","
}
}
append output "\]"
}
object {
append output "{"
set object_keys [JSON::object keys $element_value]
set key_count [llength $object_keys]
set current_index 0
foreach current_key $object_keys {
set nested_element [JSON::object get $element_value $current_key]
append output "\"${current_key}\":"
append output [call stringify $nested_element]
if {$current_index < $key_count - 1} {
append output ","
}
incr current_index
}
append output "}"
}
string - literal {
set actual_value [JSON::get $json_element $element_type]
append output "\"$actual_value\""
}
default {
set actual_value [JSON::get $json_element $element_type]
append output "$actual_value"
}
}
return $output
}
There really isn't any new magic in this proc, though I did expand variable names to make it a little more clear than our original example. It's basically a redo of the print function, but instead of printing it's just creating the string version of objects so I can execute a conditional against that string. Nothing new to learn, but necessary in making the find_key proc work.
find_key proc
proc find_key { json_element search_key } {
set element_type [JSON::type $json_element]
set element_value [JSON::get $json_element]
switch -- $element_type {
array {
set array_size [JSON::array size $element_value]
for {set index 0} {$index < $array_size} {incr index} {
set array_item [JSON::array get $element_value $index]
set result [call find_key $array_item $search_key]
if {$result ne ""} {
return $result
}
}
}
object {
set object_keys [JSON::object keys $element_value]
foreach current_key $object_keys {
if {$current_key eq $search_key} {
set found_element [JSON::object get $element_value $current_key]
set found_type [JSON::type $found_element]
if {$found_type eq "object" || $found_type eq "array"} {
set found_value [call stringify $found_element]
} else {
set found_value [JSON::get $found_element $found_type]
}
return $found_value
}
set nested_element [JSON::object get $element_value $current_key]
set result [call find_key $nested_element $search_key]
if {$result ne ""} {
return $result
}
}
}
}
return ""
}
In the find_key proc, the magic happens in line 10 for a JSON array (Tcl list) and in lines 18-32 for a JSON object (Tcl dictionary.) Nothing new in the use of the JSON commands, but rather than printing all the keys and values found, we're looking for a specific key so we can return its value. For the array we are iterating through list items that will have a single value, but that value might be an object that needs to be stringified. For the object, we need to iterate through all the keys and their values, also which might be objects or nested objects to be stringified. Recursion for the win! Hopefull you're starting to get the hang of using all the interrogating JSON commands we've covered, because now wer'e going to create something with some new commands!
iRule logic
Once we have the procs defined to handle their specific jobs, the iRule to find the key and then return the rejected status message becomes much cleaner:
when JSON_REQUEST priority 500 {
set json_data [JSON::root]
if {[call find_key $json_data "nested_array"] contains "b" } {
set cache [JSON::create]
set rootval [JSON::root $cache]
JSON::set $rootval object
set obj [JSON::get $rootval object]
JSON::object add $obj "[IP::client_addr] status" string "rejected"
set rendered [JSON::render $cache]
log local0. "$rendered"
HTTP::respond 200 content $rendered "Content-Type" "application/json"
}
}
Let's walk through this one line by line.
- Lines 1 and 13 wrap the JSON_REQUEST payload.
- Line 2 retrieves the current JSON::root, which is our payload, and stores it in the json_data variable.
- Lines 3 and 12 wrap the if conditional, which is using our find_key proc to look for the nested_array key, and if that stringified value includes b, reject the response. (in real life looking for "b" would be a terrible contains pattern to look for, but go with me here.)
- Line 4 creates a JSON context for the system. Think of this as a container we're going to do JSON stuff in.
- Line 5 gets the root element of our JSON container. At this point it's empty, we're just getting a handle to whatever will be at the top level.
- Line 6 now actually adds an object to the JSON container. At this point, it's just "{ }".
- Line 7 gets the handle of that object we just created so we can do something with it.
- Line 8 adds the key value pair of "status" and our reject message.
- Line 9 now takes the entire JSON context we just created and renders it to a JSON string we can log and respond with.
- Line 10 logs to /var/log/ltm
- Line 11 responds with the reject message in JSON format. Note I'm using a 200 error code instead of a 403. That's just because the cilent test script won't show the status message with a 403 and I wanted to see it. Normally you'd use the appropriate error code.
Now, I offer you a couple challenges.
- lines 4-9 in the JSON_REQUEST example above should really be split off to become another proc, so that the logic of the JSON_REQUEST is laser-focused. How would YOU write that proc, and how would you call it from the JSON_REQUEST event?
- The find_key proc works, but there's a Tcl-native way to get at that information with just the JSON::object subcommands that is far less complex and more performant. Come at me!
Conclusion
When I started this JSON article series, I knew A LOT less about the underlying basics of JSON than I thought I knew. It's funny how working with things on the wire requires a little more insight into protocols and data formats than you think you need. Happy iRuling out there, and I hope to see you at AppWorld next month!
Help guide the future of your DevCentral Community!
What tools do you use to collaborate? (1min - anonymous)