Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON-String to proper Object in Powershell

Tags:

powershell

I spend 3 hours debugging, but I don't get the rootcause.

I have text (in JSON Format) in a variable. I convert it with "Convert-From-JSON" to an actual object. I was hoping that I can then work with the properties of the object. But it does not work :( It seems that the conversion only gives me two tables (status and data). What am I doing wrong?

My code:

$results = {
  "status": "FINISHED",
  "data": {
    "results": [
      {
        "id": "11565C230500",
        "custom": {
          "image": "XXXX",
          "name": "XXXX",
          "articleNumber": "4032423423505"
        }
      },
      {
        "id": "22739L5F16243",
        "custom": {
          "image": "XXXX",
          "name": "XXXX",
          "articleNumber": "4032423423505"
        }
      },
      {
        "id": "3304332724004",
        "custom": {
          "image": "XXXX",
          "name": "XXXX",
          "articleNumber": "4032423423505"
        }
      }
    ]
   }
 }

Now putting it as Object:

$resultObject = ConvertFrom-JSON -InputObject $result

Now trying to retrieve:

$resultObject.id | where {$_.id -eq '11565C230500'}
like image 742
Julian Avatar asked Jul 31 '26 17:07

Julian


1 Answers

Assuming the json is single quoted in that example, otherwise it's a scriptblock, and "$results" is used in place of "$result", the id property is underneath data.results. You couldn't examine the id property with where-object if you already expanded it. That's an alternate form of where-object. I'm expanding the "custom" property with the foreach-object alias "%". Note one id number is shorter. Beware convertto-json's default depth of 2.

$results = '{"status":"FINISHED","data":{"results":[
{"id":"11565C230500", "custom":{"image":"XXXX","name":"XXXX","articleNumber":"4032423423505"}},
{"id":"22739L5F16243","custom":{"image":"XXXX","name":"XXXX","articleNumber":"4032423423505"}},
{"id":"3304332724004","custom":{"image":"XXXX","name":"XXXX","articleNumber":"4032423423505"}}
]}}'

$resultObject = ConvertFrom-JSON -InputObject $results
$resultObject.data.results | where id -eq 11565C230500

id           custom
--           ------
11565C230500 @{image=XXXX; name=XXXX; articleNumber=4032423423505}


$resultobject.data.results | where id -eq 11565C230500 | % custom

image name articleNumber
----- ---- -------------
XXXX  XXXX 4032423423505
like image 198
js2010 Avatar answered Aug 02 '26 14:08

js2010