Hashtables from ConvertFrom-json have different type from powershells built-in hashtables, how do I make them the same?

前端 未结 5 1303
天命终不由人
天命终不由人 2020-12-09 10:33

I have a json file (test.json) that looks something like this:

{
    \"root\":
    {
        \"key\":\"value\"
    }
}

I\'m loading it into

5条回答
  •  没有蜡笔的小新
    2020-12-09 10:54

    The ConvertFrom-Json cmdlet gives you a custom object so you have to access them using dot notation rather than as a subscript. Usually you would know what fields you expect in the JSON so this is actually more useful in general than getting a hash table. Rather than fighting the system by converting back to a hash table, I suggest you work with it.

    You can use select with wildcard property names to get at the properties:

    PS D:\> $data = @"
    {
        "root":
        {
            "key":"value", "key2":"value2", "another":42
        }
    }
    "@ | ConvertFrom-Json
    
    PS D:\> $data.root | select * | ft -AutoSize
    
    key   key2   another
    ---   ----   -------
    value value2      42
    
    
    
    PS D:\> $data.root | select k* | ft -AutoSize
    
    key   key2  
    ---   ----  
    value value2
    

    and Get-Member if you want to extract a list of property names that you can iterate over:

    PS D:\> ($data.root | Get-Member -MemberType NoteProperty).Name
    another
    key
    key2
    

    Putting that into a loop gives code like this:

    PS D:\> foreach ($k in ($data.root | Get-Member k* -MemberType NoteProperty).Name) {
        Write-Output "$k = $($data.root.$k)"
        }
    key = value
    key2 = value2
    

提交回复
热议问题