2

I have a json output as list, I wanted to add a property in tags parameter using PowerShell

$json = @'
[
    {
       "tags": [],
        "name": "[concat(parameters('factoryName'), '/Veh_Obj')]",
        "properties": {
            "type": "AzureDataLakeStoreFile",
        }
    }
]
'@
#$json = 'C:\workspace\cucumber_report.29776.json'

$obj = $json | ConvertFrom-Json 

# Append new objects to the array.
$obj.tags += [pscustomobject] @{ name = 'newname1' }

# Convert back to JSON.
$obj | ConvertTo-Json -Depth 10 | Set-Content $json

But i am getting error as below The property 'tags' cannot be found on this object. Verify that the property exists and can be set. looks like issue is occurs only when I am passing JSON list, with normal json input this is working fine

  • 1
    `$obj[0].tags` ? – Theo Jul 19 '21 at 17:59
  • In short: [member enumeration](https://stackoverflow.com/a/44620191/45375) - the convenient ability to get property values from all elements of a collection by using property access at the _collection_ level - by design only works for _getting_ values, not for _setting_ them - see [this answer](https://stackoverflow.com/a/64849675/45375) to the linked duplicate. – mklement0 Jul 19 '21 at 22:06

1 Answers1

2
  1. The trailing comma in line "type": "AzureDataLakeStoreFile", leads to an error ConvertFrom-Json : Invalid JSON primitive.
  2. $obj.GetType().Name returns Object[] (note that the most top element of the original json is an array []).

Use

$obj[0].tags += [pscustomobject] @{ name = 'newname1' }
JosefZ
  • 28,460
  • 5
  • 44
  • 83
  • 1
    Good point about needing `[0]` (though it's worth noting that it's only needed for _setting_, not for _getting_ the `.tags` value). Note that point 1. only applies to _Windows PowerShell_; PowerShell (Core) 7+ quietly tolerates the extraneous trailing `,`. – mklement0 Jul 19 '21 at 22:11
  • @JosefZ : Thanks a lot, comma in type i left here only while deleting the other attributes so json primitive issue was not there, but adding the index [0] solved the issue. Thanks a lot – Bhuvnesh Sainani Jul 20 '21 at 04:36