Powershell arraylist to json

Nikola Batinica 21 Reputation points
2022-03-11T15:35:00.037+00:00

i have arraylist where i am adding elements and that part work fine
{
"basePrice": 100,
"category": "some category",
"packageWeightUnit": "g",
"productType": "Some type"
}

but now i need to add to look like this
{
"basePrice": 100,
"category": "some category",
"packageWeightUnit": "g",
"productType": "Some type"
"attributes":{
"colour":["blue","red"],
hight:[100]
}

}

i use
$list = New-Object System.Collections.ArrayList

Windows for business | Windows Server | User experience | PowerShell
{count} votes

Accepted answer
  1. Michael Taylor 60,326 Reputation points
    2022-03-11T15:53:29.967+00:00

    Your description doesn't match your post title. What is your actual question?

    Both Powershell and JSON don't particularly care about the structure of your data. In PS you can have an array of various objects (it sees everything as object anyway) and JSON allows for optional fields so the missing fields in the first value won't impact the structure.

    # Using a hash object here for convenience
    $item1 = @{ basePrice = 100; category = "some category"; packageWeightUnit = "g"; productType = "Some type" }
    $item2 = @{ basePrice = 100; category = "some category"; packageWeightUnit = "g"; productType = "Some type"; attributes = @{ colour = @("blue", "red"); hight = @(100) } } 
    
    # Assuming you have more items than this...
    $list = New-Object System.Collections.ArrayList
    $list += $item1
    $list += $item2
    ConvertTo-Json $list -depth 4
    

    To go the other way, given the previous JSON

    $readItems = ConvertFrom-Json $json
    
    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Nikola Batinica 21 Reputation points
    2022-03-11T17:22:43.777+00:00

    $list.add(@{"name"=$red.name;
    "description"=$desc;
    "coverImage"=$red.coverImage;
    "ean"=$red.ean;
    "packageWeightValue"=$red.packageWeightValue;
    "packageWeightUnit"=$red.packageWeightUnit;
    "basePrice"=$red.basePrice;
    "vat"=$red.vat;
    "stockLevel"=$red.stockLevel;
    "sku"=$red.sku;
    "gallery"=$galerija;
    "brand"=$red.brand;
    "productType"=$red.productType;
    "category"=$red.category;
    attributes = @{ "key features" = @($features.naziv)}

                })
    

    and i am getting no error but output looks like
    "attributes": {
    "key features": "PARIS Hidratacija Balzam"
    },

    but it should be
    "attributes": {
    "key features": ["PARIS", "Hidratacija", "Balzam""
    },


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.