0

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!

1 Answer 1

1

...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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. And you don't even need to explain why. I can see instantly where I went wrong. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.