试图在代码中识别PS Object元素类型

时间:2017-10-16 17:15:31

标签: arrays json powershell

我是Powershell的新手。我有以下PS脚本。我试图确定powershell"代码"识别哪个字段"字段"是一个数组或哈希表。源文本是一个json文件。

$txt = @"
{
  "id": "02002010",
  "booktitle": "",
  "pagetitle": "Demo Page",
  "parent": "02002000",
  "img": [
    {
      "imgfile": "02A.png",
      "imgname": "02A.png"
    }
  ],
  "fmt": "",
  "entries": [
    {
      "itemid": "1",
      "partnumber": "1234567",
      "partdescription": "Washer",
      "partqty": "2",
      "Manufacturer": "ACME",
      "TYPE": "Stainless",
      "partdescriptionlocal": "Washer"
    },
    {
      "itemid": "2",
      "partnumber": "98765-B",
      "partdescription": "Screw",
      "partqty": "8",
      "Manufacturer": "Widget Inc",
      "TYPE": "Galv",
      "partdescriptionlocal": "Screw"
    }]
}
"@
$json=  ConvertFrom-Json -inputobject $txt
foreach($pct in $json) { 
$pct} 

脚本的输出是

id        : 02002010
booktitle : 
pagetitle : Demo Page
parent    : 02002000
img       : {@{imgfile=02A.png; imgname=02A.png}}
fmt       : 
entries   : {@{itemid=1; partnumber=1234567; partdescription=Washer; partqty=2; Manufacturer=ACME; TYPE=Stainless; 
            partdescriptionlocal=Washer}, @{itemid=2; partnumber=98765-B; partdescription=Screw; partqty=8; 
            Manufacturer=Widget Inc; TYPE=Galv; partdescriptionlocal=Screw}} 

我的问题:

什么属性/参数???将 img 条目标识为"字段"其值是数组??? 我试图在不明确知道每个字段名称的情况下使用PS识别这些字段(子阵列)。

提前致谢。

1 个答案:

答案 0 :(得分:2)

.basetype方法的.gettype()属性会为您提供:

json=  ConvertFrom-Json -inputobject $txt
foreach($pct in $json) { 
$pct.psobject.properties.name |
foreach-object {
  [PSCustomObject]@{
   Property = $_
   Type = $pct.$_.gettype().basetype
   }
 }
 }

Property  Type         
--------  ----         
id        System.Object
booktitle System.Object
pagetitle System.Object
parent    System.Object
img       System.Array 
fmt       System.Object
entries   System.Array