从JSON创建哈希表

问题描述:

我想获取Hashtable的JSON表示形式,例如:

I want to get a JSON representation of a Hashtable such as this:

@{Path="C:\temp"; Filter="*.js"}

ConvertTo-Json导致:

{
    "Path":  "C:\\temp",
    "Filter":  "*.js"
}

但是,如果使用ConvertFrom-Json将该JSON字符串转换回去,则不会得到HashTable,而是PSCustomObject.

However, if you convert that JSON string back with ConvertFrom-Json you don't get a HashTable but a PSCustomObject.

那么如何可靠地序列化上面的Hashmap?

So how can one reliably serialize the above Hashmap?

$json = @{Path="C:\temp"; Filter="*.js"} | ConvertTo-Json

$hashtable = @{}

(ConvertFrom-Json $json).psobject.properties | Foreach { $hashtable[$_.Name] = $_.Value }

改编自 PSCustomObject到Hashtable