Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a JSON in PowerShell?

Tags:

powershell

How do I create a Json in PowerShell?
I assumed it would be similar to creating Xmls in PowerShell but it doesn't work:

[Json]$MyJsonVariable = @"
{
  "MyList"{
    "Item1" {
      "Name": "AMD Ryzen 5 3600x"
      "Type":"CPU"
      "Price":"`$69.99"
      "Where":"Amazon.com"
    }
  }
}
"@

But it didn't work:

Unable to find type [Json].
At line:1 char:1
+ [Json]$MyJsonVariable = @"
+ ~~~~~~
    + CategoryInfo          : InvalidOperation: (Json:TypeName) [], RuntimeException
    + FullyQualifiedErrorId : TypeNotFound

Help Please

like image 714
Nikola Johnson Avatar asked Dec 22 '25 05:12

Nikola Johnson


1 Answers

Give this a try:

$MyJsonHashTable = @{
  'MyList' = @{
    'Item1' = @{
      'Name' = 'AMD Ryzen 5 3600x'
      'Type' = 'CPU'
      'Price' = '$69.99'
      'Where' = 'Amazon.com'
    }
  }
}

$MyJsonVariable = $MyJsonHashTable | ConvertTo-Json

$err = $null
$MyJsonObject = [Microsoft.PowerShell.Commands.JsonObject]::ConvertFromJson($MyJsonVariable, [ref]$err)

The result is a $MyJsonVariable that contains a Json string:

{
    "MyList":  {
                   "Item1":  {
                                 "Price":  "$69.99",
                                 "Where":  "Amazon.com",
                                 "Name":  "AMD Ryzen 5 3600x",
                                 "Type":  "CPU"
                             }
               }
}

And a $MyJsonObject that contains a Json object reference:

MyList
------
@{Item1=}

I suspect one of these 3 PowerShell variables should be suitable for your Json needs.

Hope this helps.

like image 110
leeharvey1 Avatar answered Dec 23 '25 18:12

leeharvey1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!