by: Helge, published: Mar 29, 2021, in

Splunk Search Results: JSON to HTML Table Conversion in PowerShell

Splunk search results can be exported from the UI as CSV, JSON, and XML, but not as HTML. This article presents a PowerShell script that converts exported search results from JSON into an HTML table for use with documentation, blogs, etc.

Format of Splunk Search Results Exported to JSON

JSON files with exported Splunk search results have the following structure:

{"preview":false,"result":{"field1":"value1-1","field2":"value2-1"}}
{"preview":false,"lastrow":true,"result":{"field1":"value1-2","field2":["value2-2a","value2-2b"]}}

As you can see, each line is an independent JSON object. Most likely you’re not interested in metadata, only in the fields returned from your search. The fields and their values are encapsulated in the result object.

Splunk searches may return multiple values per field. Such multivalue fields are represented as JSON arrays in the export, as shown in the value for field2 in the second row of the example above. The conversion script deals with multivalue fields correctly, separating individual values by line breaks.

Conversion Script

Without further ado, this is the PowerShell script to convert Splunk’s JSON export into a nicely formatted HTML table:

param ([Parameter(Mandatory)] $inputFile, [Parameter(Mandatory)] $outputFile)

$newline          = [Environment]::NewLine
[bool] $firstLine = $true

# Loop over all search results (each line in the export is one result)
Get-Content $inputFile | ForEach-Object {
   $json = $_ | ConvertFrom-Json

   if ($firstLine)
   {
      $output  = "<table>$newline"
      $output += "   <thead>$newline"
      $output += "      <tr>$newline"

      # Iterate over all fields in this search result
      ForEach ($field in $json.result.PsObject.Properties) {
         $output += "         <th>$($field.Name)</th>$newline"
      }

      $output += "      </tr>$newline"
      $output += "   </thead>$newline"
      $output += "   <tbody>$newline"
   }

   $output += "      <tr>$newline"

   # Iterate over all fields in this search result
   ForEach ($field in $json.result.PsObject.Properties) {
      # Each field could be multivalue -> join
      $value = $field.Value -join "<br>"

      $output += "         <td>$value</td>$newline"
   }

   $output += "      </tr>$newline"

   $firstLine = $false
}

$output += "   </tbody>$newline"
$output += "</table>$newline"

Set-Content -Path $outputFile -value $output

Previous Article Adobe Acrobat & Photoshop: Network Connection Target Hosts
Next Article Royalty-Free Images for Blogs, Websites & Social Media