Create hash table from JSON

Hi,

I am trying to create a hashtable from JSON but not able to create a hashtable correctly in custom_fields_values section. Below is my code. Please help.

$JSON = @"
{
  "hardware": {
    "name": $Name,
    "status": {
      "name": "Operational"
    },
    "owner": {
      "email": $Email
    },
    "custom_fields_values": {
      "custom_fields_value": [
        {
          "name": "Deployment Status",
          "value": "Repairs"
        }
      ]
    }
  }
}

"@

$Hashtable = @{
           hardware = @{
                        name = $Name
                        bio = @{
                            'ssn'  = $SerialNumber
                       }

                       status = @{
                            'name' = "Operational"
                        }

                        owner = @{
                              'email' = $Email
                     }

                        custom_fields_values = @{
                        custom_fields_value = @{
                        
                            'name' = "Deployment Status"
                            'value' = "Repairs"
                        }
                        }
                    }
               }

As your JSON data are hierarchical data it will not be as straight forward as you might think. You would need to follow the branches to be able to create sub hashtables.

May I ask why you need the JSON as hashtable? Did you try to use ConvertFrom-JSON and use the resulting object for your purpose?

BTW: Your JSON data seems to be invalid. I’m not an expert for JSON but I think you have to wrap your variables in quotes.

Assumed I’m right and you use ConvertFrom-JSON like this:

$Name = 'Buddy'
$Email = 'Buddy@Mail.net'

$JSON = @"
{
  "hardware": {
    "name": "$Name",
    "status": {
      "name": "Operational"
    },
    "owner": {
      "email": "$Email"
    },
    "custom_fields_values": {
      "custom_fields_value": [
        {
          "name": "Deployment Status",
          "value": "Repairs"
        }
      ]
    }
  }
}
"@ | ConvertFrom-Json

You can access all elements with the dot-notation like this:

$JSON.hardware.owner.email

And the reult would be:

Buddy@Mail.net

:+1:t4:

1 Like

@Olaf I did not tried to use double quotes in JSON but I tried now and It works.

Thanks alot