2

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

0

1 Answer 1

3

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"
  }
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.