Question:
I have an array of JSON objects and I want to add a particular property to each object present.
For example, the array is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
[ { "Average": 1.3085, "ExtendedStatistics": { }, "Maximum": 0, "Minimum": 0, "SampleCount": 0, "Sum": 0, "Timestamp": "\/Date(1496972280000)\/", "Unit": { "Value": "Percent" } }, { "Average": 1.4324999999999999, "ExtendedStatistics": { }, "Maximum": 0, "Minimum": 0, "SampleCount": 0, "Sum": 0, "Timestamp": "\/Date(1496944680000)\/", "Unit": { "Value": "Percent" } } ] |
I want to add “source”: “CPU” to all objects. How do I go about doing that? I am new to PowerShell and haven’t been able to get this done.
Answer:
You could do the following:
1 2 3 4 |
$JSON | ConvertFrom-Json | ForEach-Object { $_ | Add-Member -MemberType NoteProperty -Name 'Source' -Value 'CPU' -PassThru } | ConvertTo-Json |
This assumes your JSON input is in a variable named $JSON
, you’ll need to replace this with however you access your JSON content (e.g Get-Content yourfile.json
).
Once you have the JSON, we use ConvertFrom-JSON
to convert it to a PowerShell object.
We then use the pipeline to send this to a ForEach-Object
loop which uses the Add-Member
cmdlet to add a property to each item in the collection (the current item is represented by $_
) named ‘Source’ with a value of ‘CPU’. Per the comments from mklement0, it is necessary to use the -PassThru
switch to send the result back to the pipeline.
Then we pipe that output to ConvertTo-JSON to convert it back.