Iterating through a JSON file PowerShell

前端 未结 3 1087
孤街浪徒
孤街浪徒 2020-11-27 05:30

I am trying to loop through the below JSON file in PowerShell.

Without specifically naming the top tags (e.g. 17443 and 17444), as I do not know them in advance I ca

3条回答
  •  余生分开走
    2020-11-27 06:10

    This question comes up a lot. In this case we have to loop over properties twice. This is my current answer. Make the object a little easier to work with. Both the top level and the data properties become arrays of "name" and "value". You could use select-object calculated properties to present it any way you want. It seems like in json you more often get random properties, rather then an array of the same properties.

    $a = cat file.json | convertfrom-json
    
    $a = $a.psobject.properties | select name,value 
    $a | foreach { $_.value.data = 
      $_.value.data.psobject.properties | select name,value }
    
    $a.value.data.value
    
    value
    -----
    {Mr}
    {Jack}
    {Cawles}
    {Miss}
    {Charlotte}
    {Tann}
    {Mr}
    {John}
    {Brokland}
    

    Trying something similar with jq:

    '{"prop1":1, "prop2":2, "prop3":3}' | jq to_entries | convertfrom-json
    
    key   value
    ---   -----
    prop1     1
    prop2     2
    prop3     3
    
    

    Also convertFrom-Json in Powershell 7 has an -AsHashTable parameter, that gives you keys and values properties.

    $a = '{"name":"joe","address":"here"}' | ConvertFrom-Json -AsHashtable
    $a
    
    Name                           Value
    ----                           -----
    name                           joe
    address                        here
    
    $a.keys
    name
    address
    
    $a.values
    joe
    here
    

提交回复
热议问题