【发布时间】:2014-03-27 00:00:23
【问题描述】:
我有一个看起来像这样的 json 文件 (test.json):
{
"root":
{
"key":"value"
}
}
我正在使用类似这样的方式将其加载到 powershell 中:
PS > $data = [System.String]::Join("", [System.IO.File]::ReadAllLines("test.json")) | ConvertFrom-Json
root
----
@{key=value}
我希望能够枚举由 json 文件定义的“哈希表”类对象的键。因此,理想情况下,我希望能够做一些事情喜欢:
$data.root.Keys
然后取回 ["key"]。我可以使用 powershell 中的内置哈希表来执行此操作,但是使用从 json 加载的哈希表执行此操作不太明显。
在解决此问题时,我注意到 ConvertFrom-json 返回的字段类型与 Powershell 哈希表的类型不同。例如,在内置哈希表上调用 .GetType() 会显示它是“哈希表”类型:
PS > $h = @{"a"=1;"b"=2;"c"=3}
PS > $h.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Hashtable System.Object
对我的 json 对象执行相同操作会产生 PSCustomObject:
PS > $data.root.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False PSCustomObject System.Object
有没有办法将此对象转换或转换为典型的 powershell Hashtable?
【问题讨论】:
-
我看到了这个链接 (stackoverflow.com/questions/3740128/pscustomobject-to-hashtable),它看起来很相关,但对我来说不太有用。
标签: json powershell