Test-Json
測試字串是否為有效的 JSON 檔
語法
Test-Json
[-Json] <String>
[<CommonParameters>]
Test-Json
[-Json] <String>
[[-Schema] <String>]
[<CommonParameters>]
Test-Json
[-Json] <String>
[-SchemaFile <String>]
[<CommonParameters>]
Description
Cmdlet Test-Json
會測試字串是否為有效的 JavaScript 物件表示法 (JSON) 檔,並可選擇性地根據提供的架構驗證 JSON 檔。
然後,驗證的字串可以與 ConvertFrom-Json
Cmdlet 搭配使用,將 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:
Line |
35 | '{"name": "Ashley", "age": "25"}' | Test-Json -Schema $schema
| ~~~~~~~~~~~~~~~~~~~~~~~~~
| IntegerExpected: #/age
False
在此範例中,我們會收到錯誤,因為架構預期存留期為整數,但我們測試的 JSON 輸入會改用字串值。
如需詳細資訊,請參閱 JSON 架構。
範例 3:從檔案對架構測試物件
JSON 架構可以使用 關鍵詞來參考定義 $ref
。 $ref
可以解析為參考另一個檔案的 URI。 SchemaFile 參數接受 JSON 架構檔案的常值路徑,並允許針對這類架構驗證 JSON 檔案。
在這裡範例中,檔案 schema.json
會參考 definitions.json
。
Get-Content schema.json
{
"description":"A person",
"type":"object",
"properties":{
"name":{
"$ref":"definitions.json#/definitions/name"
},
"hobbies":{
"$ref":"definitions.json#/definitions/hobbies"
}
}
}
Get-Content definitions.json
{
"definitions":{
"name":{
"type":"string"
},
"hobbies":{
"type":"array",
"items":{
"type":"string"
}
}
}
}
'{"name": "James", "hobbies": [".NET", "Blogging"]}' | Test-Json -SchemaFile 'schema.json'
True
如需詳細資訊,請參閱 建構複雜的架構。
參數
-Json
指定要測試有效性的 JSON 字串。 輸入包含字串的變數,或輸入取得字串的命令或表達式。 您也可以使用管線將字串傳送至 Test-Json
。
需要 Json 參數。
類型: | String |
Position: | 0 |
預設值: | None |
必要: | True |
接受管線輸入: | True |
接受萬用字元: | False |
-Schema
指定要驗證 JSON 輸入的架構。 如果傳遞,Test-Json
驗證 JSON 輸入是否符合 Schema 參數指定的規格,而且只有在輸入符合提供的架構時,才會傳回 $true
。
如需詳細資訊,請參閱 JSON 架構。
類型: | String |
Position: | 1 |
預設值: | None |
必要: | False |
接受管線輸入: | False |
接受萬用字元: | False |
-SchemaFile
指定用來驗證 JSON 輸入的架構檔案。 使用時,Test-Json
只有在 JSON 輸入符合 SchemaFile 參數所指定檔案中所定義的架構時,才會傳回 $true
。
如需詳細資訊,請參閱 JSON 架構。
類型: | String |
Position: | 1 |
預設值: | None |
必要: | False |
接受管線輸入: | False |
接受萬用字元: | False |
輸入
您可以使用管線將 JSON 字串傳送至此 Cmdlet。
輸出
Boolean
如果 JSON 有效,則此 Cmdlet 會傳 $true
回 ,否則 $false
為 。
備註
Cmdlet Test-Json
是使用 NJsonSchema 類別實作。
由於 PowerShell 6,PowerShell 會針對所有 JSON 函式使用 Newtonsoft.Json 元件。 Newtonsoft 的實作包含數個 JSON 標準的延伸模組,例如支援批注和使用單引號。 如需功能的完整清單,請參閱 上的 Newtonsoft 檔 https://www.newtonsoft.com/json。