Test-Json
测试字符串是否为有效的 JSON 文档
语法
Test-Json
[-Json] <string>
[[-Schema] <string>]
[<CommonParameters>]
说明
cmdlet Test-Json
测试字符串是否是有效的 JavaScript 对象表示法 (JSON) 文档,并且可以根据提供的架构选择性地验证 JSON 文档。
然后,可以将已验证的字符串与 cmdlet 一起使用 ConvertFrom-Json
,将 JSON 格式的字符串转换为 JSON 对象,该对象可在 PowerShell 中轻松管理,或者发送到访问 JSON 输入的其他程序或 Web 服务。
许多网站使用 JSON(而不是 XML)来序列化用于在服务器和基于 Web 的应用之间进行通信的数据。
此 cmdlet 是在 PowerShell 6.1 中引入的
示例
示例 1:测试对象是否为有效的 JSON
此示例测试输入字符串是否为有效的 JSON 文档。
"{'name': 'Ashley', 'age': 25}" | Test-Json
True
示例 2:根据提供的架构测试对象
此示例采用包含 JSON 架构的字符串,并将其与输入字符串进行比较。
$schema = @'
{
"definitions": {},
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "http://example.com/root.json",
"type": "object",
"title": "The Root Schema",
"required": [
"name",
"age"
],
"properties": {
"name": {
"$id": "#/properties/name",
"type": "string",
"title": "The Name Schema",
"default": "",
"examples": [
"Ashley"
],
"pattern": "^(.*)$"
},
"age": {
"$id": "#/properties/age",
"type": "integer",
"title": "The Age Schema",
"default": 0,
"examples": [
25
]
}
}
}
'@
"{'name': 'Ashley', 'age': '25'}" | Test-Json -Schema $schema
Test-Json : IntegerExpected: #/age
At line:1 char:37
+ "{'name': 'Ashley', 'age': '25'}" | Test-Json -Schema $schema
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Test-Json], Exception
+ FullyQualifiedErrorId : InvalidJsonAgainstSchema,Microsoft.PowerShell.Commands.TestJsonCommand
False
在此示例中,我们收到错误,因为架构需要 一个整数来表示年龄 ,但我们测试的 JSON 输入改用字符串值。
有关详细信息,请参阅 JSON 架构。
参数
-Json
指定要测试有效性的 JSON 字符串。 输入一个包含字符串的变量,或键入可获取字符串的命令或表达式。 还可以通过管道将字符串传递给 Test-Json
。
Json 参数是必需的。
Type: | String |
Position: | 1 |
Default value: | None |
Required: | True |
Accept pipeline input: | True |
Accept wildcard characters: | False |
-Schema
指定要验证 JSON 输入的架构。 如果传递, Test-Json
将验证 Json 输入是否符合 Schema 参数指定的规范,并且仅在输入符合提供的架构时返回 $True
。
有关详细信息,请参阅 JSON 架构。
Type: | String |
Position: | 2 |
Default value: | None |
Required: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
输入
可以通过管道将 JSON 字符串传递给 Test-Json
。
输出
Boolean
备注
cmdlet Test-Json
是使用 NJsonSchema 类实现的。