共用方式為


Test-Json

測試字串是否為有效的 JSON 檔

Syntax

Test-Json
    [-Json] <string>
    [[-Schema] <string>]
    [<CommonParameters>]

Description

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

輸入

String

您可以使用管線將 JSON 字串傳送至 Test-Json

輸出

Boolean

備註

Cmdlet Test-Json 是使用 NJsonSchema 類別來實作。