I’m looking for a way to check if file provided to the script matches a schema that is required by the script. My powershell version is 5 so no access to Test-Json cmndlet. Any ideas?
JSON schema to be checked against.
$json_content = @"
{
"buttons":{
"1":"Zenek",
"2":"NetExt"
},
"Text":{
"1":"",
"2":""
}
}
"@
Example file to be checked (positively)
$json_content = @"
{
"buttons":{
"1":"Zenek",
"2":"NetExt"
},
"Text":{
"1":"THIS IS OK",
"2":"CORRECT"
}
}
"@
Example file 2 to be checked (and failed)
$json_content = @"
{
"I MADE CHANGES HERE":{
"1":"Zenek",
"2":"NetExt"
},
"PLEAE FAIL ME":{
"1":"",
"2":""
}
}
"@
2
Answers
PowerShell 7 comes with
Test-Json
, a command with which you can validate a JSON document against a JSON schema.First, we’ll need to define a schema that describes the required JSON format:
Here, we describe a root object with two properties,
buttons
andText
, both of which are required to have a value described by the nestedstringtuple
schema – an object that consists of two string properties1
and2
.Now it’s simply a question of calling
Test-Json
:This approach will compare the
noteproperty
members between 2 PSObjects and will return false if any of the following occurs:The basic idea is:
psCustomObjects
.noteproperties
of the highest level object of the template and target.psCustomObjects
(but return false as soon as a mismatch is found)Please note that this will only work with
noteproperties
. If you try to compare complex objects containing methods or other property types then this will not work.Test Data:
Function for comparing the object structures:
Function for seeing what the custom
Verify-PSObjectStructure
function is doing: