1

I have below JSON file that gets parsed with ConvertFrom-Json command:

{
  "item1": {
    "class": "class1",
    "price": "price1"
  },
  "item2": {
    "class": "class2",
    "price": "price2"
  }
}

This creates a PSCustomObject with two properties item1 and item2. It produces below output:

item1                         item2
-----                         -----
@{class=class1; price=price1} @{class=class2; price=price2}

What I need instead is an array that prints:

name  class  price
----  -----  -----
item1 class1 price1
item2 class2 price2

Please note that I cannot modify the content of JSON file.

Any kind of help is much appreciated.

2 Answers 2

4

Found the solution in my colleague's code:

$json = Get-Content -Path "<file-path>" | ConvertFrom-Json;
$json.PSObject.Properties | ForEach-Object { [PSCustomObject] @{
    name = $_.Name;
    class = $_.Value.class;
    price = $_.Value.price;
}}
Sign up to request clarification or add additional context in comments.

Comments

1

This one gives you all item-attributes and adds the name. The result is an array of objects:

$result = foreach($item in $json.PsObject.Properties) {
    Add-Member -in $item.value -NotePropertyName 'name' -NotePropertyValue $item.name –PassThru
}

Comments

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.