代码之家  ›  专栏  ›  技术社区  ›  epitka

如何在Powershell中将json转换成散列?

  •  0
  • epitka  · 技术社区  · 4 年前

    我需要把json转换成ps散列对象。我试过了

    $data = $event | Select-Object -ExpandProperty data -First 1;

    1 回复  |  直到 4 年前
        1
  •  0
  •   Sage Pourpre    4 年前

    你要找的是 ConvertFrom-Json

    如果$event contain是您的json,那么您应该:

    $data = $event | ConvertFrom-Json $event 存储在 $data

    完整的可复制示例

    
    # Just a random JSON found elsewhere to demonstrate the cmdlet used afterward.
    $JsonExample = @"
    {
       "countries":[
          {
             "name":"USA",
             "grandfathers":[
                {
                   "gFName":"Steve",
                   "grandfathersKid":[
                      {
                         "gFKName":"Linda",
                         "kid":[
                            {
                               "name":"Steve JR",
                               "friends":[
                                  {
                                     "name":"Kriss|John|Martin|Steven"
                                  }
                               ]
                            }
                         ]
                      }
                   ]
                }
             ]
          }
       ]
    }
    "@
    
    # Convert Json input into PSObject
    $MyObject = $JsonExample | ConvertFrom-Json
    
    # Will returns the list of grandfathers from the first (and only in this case) country.
    $MyObject.countries[0].grandfathers