Home > OS >  How to add a value to an existing JSON object via Powershell
How to add a value to an existing JSON object via Powershell

Time:06-13

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?

CodePudding user response:

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"
                              ]
              }
}

CodePudding user response:

You might simply replace the Attribute "Machine" with its new value like:

$dacpacvariable = $dacpacvariable.Scope.Machine = $dacpacvariable.Scope.Machine   "Machines-2"
  • Related