Sar
Sar

Reputation: 299

To delete loop inside a variable using powershell

enter image description here

I did invoke-restmethod and stored the output in variable $a and used convertTo-json and i want to remove the variables and values which are not required. I have used $a -replace "variables" -replace "value" but it's not working

Upvotes: 2

Views: 250

Answers (1)

mklement0
mklement0

Reputation: 437638

Don't try to manipulate JSON as text (as a string).

It's easier and more robust to transform the _objects ([pscustomobject] instances) representing the input JSON that Invoke-RestMethod returns:

# Assume that $fromJson was obtained as follows:
#   $fromJson = Invoke-RestMethod ...

$fromJson.variables | ForEach-Object {
  # Replace the property values with the current value's .value property
  # value.
  foreach ($prop in $_.psobject.Properties) {
    $_.($prop.Name) = $prop.Value.value
  }
  $_  # Output the modified object.
} | ConvertTo-Json

$json.variables uses member-access enumeration to return an array of the variables property values, and the ForEach-Object command transforms the resulting objects by replacing their property values with their .value property value.

.psobject.Properties is a way of reflecting on any object's properties, and each property-information object returned has a .Name and a .Value property.

ConvertTo-Json converts the modified objects back to JSON

Given the following sample JSON input:

[
  {
    "variables": {
      "appdata": {
        "value": "x1"
      },
      "appinsta": {
        "value": "y1"
      }      
    }   
  },
  {
    "variables": {
      "appdata": {
        "value": "x2"
      },
      "appinsta": {
        "value": "y2"
      }      
    }   
  }
]

the above outputs:

[
  {
    "appdata": "x1",
    "appinsta": "y1"
  },
  {
    "appdata": "x2",
    "appinsta": "y2"
  }
]

Upvotes: 3

Related Questions