Exploring the PowerShell Cmdlet: Test-Json
Welcome back to Wahman’s PowerShell blog! Today, we’ll dive into a handy cmdlet that can be incredibly helpful for validating your data formats: Test-Json. As the name suggests, this cmdlet checks whether a string is a valid JSON document. JSON (JavaScript Object Notation) is a widely used data format, especially when working with REST APIs, configuration files, or data exchange between services.
Why Use Test-Json?
Whenever you’re dealing with JSON in PowerShell—be it fetching API responses, parsing config files, or building scripts for automation—you want to ensure you’re working with valid JSON. Invalid JSON can lead to script errors, incomplete data parsing, or unexpected behaviors.
Enter Test-Json. It’s simple to use yet powerful for both everyday scripting and more advanced automation tasks.
Example 1: Basic JSON String Validation
$json = '{ "name": "Alice", "age": 30 }'
Test-Json -Json $json
This will return True because the string is a valid JSON document.
Example 2: Invalid JSON Detection
$badJson = '{ "name": "Bob", "missingQuote: 40 }'
Test-Json -Json $badJson
This will return False because the second key is missing a closing quote.
Example 3: Validating JSON from a File
$jsonFile = Get-Content -Path ".\config.json" -Raw
if (Test-Json -Json $jsonFile) {
Write-Output "JSON file is valid."
} else {
Write-Output "Invalid JSON in file."
}
This is particularly useful when loading external config files or data exports that need validation before processing them further.
Example 4: Using Test-Json with Schemas (Advanced)
Starting with PowerShell 7, Test-Json supports JSON Schema validation! This is a game changer for enforcing structured data format validation.
$json = '{ "username": "admin", "role": "superuser" }'
$schema = '{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"username": {"type":"string"},
"role": {"type":"string"}
},
"required": ["username", "role"]
}'
Test-Json -Json $json -Schema $schema
This will return True if the JSON structure conforms to your defined schema. Very handy when you want to ensure correctness of input before proceeding.
Wrap Up
The Test-Json cmdlet is an excellent tool for both beginners and pros alike. From simple string validation to schema-driven verification, knowing how to use this cmdlet will greatly enhance your PowerShell scripting toolkit.
Happy scripting, and I will see you in the next post!
Leave a Reply