How to add a value to an existing JSON object via Powershell - arrays

I have pulled a large amount of data from a website via REST and converted it to JSON.
I have extracted the specific entry in JSON I need to edit. See below
$variables = contains all the data converted to JSON
$dacpacvariable = contains the specific entry I need to edit (which is below)
{
"Id": "c1f4fe9b-3c4d-8j02-0e7x-0a6528bn192c",
"Name": "Variable1",
"Value": "abc123",
"Description": null,
"Scope": {
"Machine": [
"Machines-1"
]
},
}
I need to edit the scope section to look like the following:
"Scope": {
"Machine": [
"Machines-1",
"Machines-2"
]
},
And then add the whole entry with the edited scope back to the larger JSON.
Any ideas?

You might simply replace the Attribute "Machine" with its new value like:
$dacpacvariable = $dacpacvariable.Scope.Machine = $dacpacvariable.Scope.Machine + "Machines-2"

Do you mean something like this:
$json = #'
{
"Id": "c1f4fe9b-3c4d-8j02-0e7x-0a6528bn192c",
"Name": "Variable1",
"Value": "abc123",
"Description": null,
"Scope": {
"Machine": [
"Machines-1"
]
}
}
'# | ConvertFrom-Json
$json.Scope.Machine += 'Machines-2'
$json | ConvertTo-Json # -Depth 99 unsure how many nestings there are in the complete json
Output:
{
"Id": "c1f4fe9b-3c4d-8j02-0e7x-0a6528bn192c",
"Name": "Variable1",
"Value": "abc123",
"Description": null,
"Scope": {
"Machine": [
"Machines-1",
"Machines-2"
]
}
}

Related

Powershell 7.2.5 ConvertFrom-Json Outputting Array as One Object

I'm using the AWS CLI command aws iam list-users in Powershell 7.2.5 and trying to convert the output from JSON to a Powershell Object.
The JSON output of the above command looks like this (actual values omitted):
{
"Users": [
{
"Path": "/",
"UserName": "username1",
"UserId": "userid1",
"Arn": "arnid1",
"CreateDate": "createddate"
},
{
"Path": "/",
"UserName": "username2",
"UserId": "userid2",
"Arn": "arnid2",
"CreateDate": "createddate"
},
{
"Path": "/",
"UserName": "username3",
"UserId": "userid3",
"Arn": "arnid3",
"CreateDate": "createddate"
}
]
}
When I try and run the following code to create an array of Powershell Objects the output comes out as one Object.
$users = ConvertFrom-Json -InputObject $usersJson
Users
-----
{#{Path=/; UserName=username1; UserId=userid1; Arn=arnid1; CreateDate=createddate}, #{Path=/; UserName=username2; UserId=userid2; Arn=arnid2; CreateDate=createddate}, #{Path=/; UserName=username3; UserId=userid3; Arn=arnid3; CreateDate=createddate}}
Have read over countless posts and am now at a loss of what to do.
Any help would be greatly appreciated.
Santiago's comment was correct:
$users.Users shows all the entries as individual objects.

How to add objects to a blank array in a json file using powershell

here is my json body .
{
"source": 2,
"revision": 3,
"description": null,
"triggers": [],
"releaseNameFormat": "Release-$(rev:r)",
"tags": [],
"pipelineProcess": {
"type": 1
},
"properties": {
"DefinitionCreationSource": {
"$type": "System.String",
"$value": "BuildSummary"
},
"System.EnvironmentRankLogicVersion": {
"$type": "System.String",
"$value": "2"
}
},
"id": 5,
"name": "CheckListAPI - CD",
"path": "\\Admin",
"projectReference": null,
"url": "",
"_links": {
"self": {
"href": ""
},
"web": {
"href": ""
}
}
}
I want to add some values inside the brackets at "triggers": [],
What I'm trying to get is:
"triggers":
[
{
"artifactAlias": "_DV_NJ_PIPE",
"triggerConditions": [],
"triggerType": 1
}
],
i tried -replace and replace() saving the json file to local system, but none of them are working, I even tried to edit the json file directly like this but failed.
$alias = $json.triggers
foreach ($artifact in $alias )
{
$artifact.artifactAlias = "_$DefName"
$artifact.triggerConditions = "{}"
$artifact.triggertype = "artifactSource"
}
Please help.
You can import the json file as PowerShell objects, manipulate the structure until it looks the way you want it to and export it back to json format:
$pipeline = Get-Content .\input.json | ConvertFrom-Json
$trigger = [ordered]#{
artifactAlias = "_DV_NJ_PIPE"
triggerConditions = #()
triggerType = 1
}
$pipeline.triggers += $trigger
$pipeline | ConvertTo-Json -Depth 5 | Out-File .\output.json
As it was pointed out in the comments, it is of course also possible to import the trigger definition from a json file instead of building it in a hash table.

Powershell and Nested JSON [duplicate]

This question already has answers here:
Unexpected ConvertTo-Json results? Answer: it has a default -Depth of 2
(2 answers)
Closed 3 years ago.
I have the following JSON
{
"method": "exec",
"params": [
{
"url": "/sys/login/user",
"data": [
{
"user": "MyUsername",
"passwd": "MyPassword"
}
]
}
],
"id": 1,
"ver": "2.0"
}
I'm trying to build this JSON using Powershell, but the output is not correct, below is my code.
$fullJson=#{}
$params=#()
$paramsdata=#()
$paramsdata+=#{"user"="mailapi"}
$paramsdata+=#{"passwd"="**********"}
$params+=#{"url"="/sys/login/user"}
$params+=#{"data"=$paramsdata}
$fullJson.Add("method", "exec")
$fullJson.Add("params",$params)
$fullJson.Add("id", "1")
$fullJson.Add("ver", "2.0")
$JsonBody=$fullJson | ConvertTo-Json
$x=Invoke-WebRequest -Uri https://10.10.10.10/jsonrpc -Body $JsonBody -Method Post
The output is the below
{
"method": "exec",
"params": [
{
"url": "/sys/login/user"
},
{
"data": "System.Collections.Hashtable System.Collections.Hashtable"
}
],
"id": "1",
"ver": "2.0"
}
The problem is DATA properties is not correct format, it should be an a nested array inside the first one, but it seems that its being added as a hashtable.
This problem is the data array should be built like this one below
"params": [
{
"url": "/sys/login/user",
"data": [
{
"user": "MyUsername",
"passwd": "MyPassword"
}
]
But with my code, its being built like this
"params": [
{
"url": "/sys/login/user"
},
{
"data": "System.Collections.Hashtable System.Collections.Hashtable"
}
],
Any help in updating this.
Thanks
Use the -Depth option in ConvertTo-Json :
Specifies how many levels of contained objects are included in the
JSON representation. The default value is 2.
Your desired depth is 4 (object -> params -> data -> username/password) :
$JsonBody=$fullJson | ConvertTo-Json -Depth 4

PowerShell: Add Array with mutliple values to value field in JSON

I have some restmethods with powershell (VMWare vRA API) where I get a template for a development request and then I need to fill that (JSON format).
The "data" part of the template has different properties like:
Name : Test
selectedNetworks :
selectedServices :
My question:
How do I get my array $networks (network1,network2,network3) to fill the json element "selectedNetworks" that it becomes like this:
"key": "selectedNetworks",
"value": {
"type": "multiple",
"elementTypeId": "STRING",
"items": [
{
"type": "string",
"value": "network1"
},
{
"type": "string",
"value": "network2"
},
{
"type": "string",
"value": "network3"
}
]
}
I know how to add in "simple" values like the name is
$WebRequestBodyData.Name="$Name"
But how do I get the complex format above into $WebRequestBodyData.selectedNetworks?
Any help is greatly appreciated!
Thanks and best regards,
Ville
I could solve it like that:
$networkjson = '{"type": "multiple", "elementTypeId": "STRING", "items": [] }' | ConvertFrom-Json
foreach($nwitem in $networks){
$networkjson.items += $nwitem
}
$BodyData.selectedNetworks += $networkjson

Node.JS - How to access Values of Dictionary within an Array of a Key in a Dictionary?

I'm new in Node.JS and I'm able to parse the JSON data and do a console log to print out name and badges.
var details = JSON.parse(body);
console.log(details.name, details.badges.length);
But I don't know how I can get the data inside the arrays of the bagdes such as id, name, url.
I tried
console.log(details.badges.length.id);
But nothing shows up. How can I access that? Thank you.
{
"name": "Andrew Chalkley",
"badges": [
{
"id": 49,
"name": "Newbie",
"url": "http:\/\/teamtreehouse.com\/chalkers",
"icon_url": "https:\/\/achievement-images.teamtreehouse.com\/Generic_Newbie.png",
"earned_date": "2012-07-23T19:59:34.000Z",
"courses": [
]
},
{
"id": 26,
"name": "Introduction",
"url": "http:\/\/teamtreehouse.com\/library\/html\/introduction",
"icon_url": "https:\/\/achievement-images.teamtreehouse.com\/HTML_Basics.png",
"earned_date": "2012-07-23T21:57:24.000Z",
"courses": [
{
"title": "HTML",
"url": "http:\/\/teamtreehouse.com\/library\/html",
"badge_count": 1
},
{
"title": "Introduction",
"url": "http:\/\/teamtreehouse.com\/library\/html\/introduction",
"badge_count": 1
}
]
}
}
It is an array, so you need the index, for example: details.badges[0].id
This will return the first (index 0) element id.
.length only returns the length of the array, so it will not be useful to get the data in it.

Resources