Home > Back-end >  Powershell, JSON and Hashtables
Powershell, JSON and Hashtables

Time:09-27

My JSON

[
  {
    "solution": "abc",
    "solutionName": "abc_test",
    "solutionShortcode": "",
    "isManaged": false
  },
  {
    "solution": "def",
    "solutionName": "def_test",
    "solutionShortcode": "def1",
    "isManaged": true
  }
]

What I need to do is take the solutionName and the solutionShortcode from each and insert them into a new hashtable - i thought this would work...

      $buildDictionary = @{}
      $b = Get-Content -Raw -Path ./temp.json | ConvertFrom-Json
      foreach ($a in $b.solutionName.GetEnumerator()) {
        $name = $b.solutionName.toString()
        $shortcode = $b.solutionShortcode.toString()
        if ([string]::IsNullOrEmpty($shortcode)) {
        $shortcode = "0xxx"
        }
        $buildDictionary.Add("$name","$shortcode")
      }
      Write-Output $buildDictionary

Basically what I need to do is not that complex but there must be something I am missing about the ConvertFrom-Json cmdlet because this is not working as expected.

Essentially I need to add a generic value if the "shortcode" is empty and take insert the solutionName and solutionShortcode into the "buildDictionary" hashtable as a key/value pair.

What I have currently errors with "Key already added" error messages.. my resulting hashtable ends up with a single row consisting of a System.Object and not a key=value pair with string content.

Would appreciate some insight into what is wrong and why it is wrong. Thanks!

CodePudding user response:

...should do what you want:

$buildDictionary = @{}
$json = ConvertFrom-Json -InputObject (gc '.\temp.json' -raw)
$json | %{
    If (!$_.solutionShortCode){
        $_.solutionShortCode = 'someValue'
        $buildDictionary.add($_.solutionName,$_.solutionShortcode)
    }
}

If solutionShortCode is empty it sets 'someValue' as value and adds solutionName as Key to the HashTable $buildDictionary with the value solutionShortCode.

  • Related