mclark1129
mclark1129

Reputation: 7592

Update JSON file without destroying JSON format

I'm trying to update a Swagger JSON document in Powershell. I need to add a couple of properties and values if they do not already exist on the object.

The code for doing this is pretty simple:

$swaggerDoc = (Get-Content $filePath -raw | ConvertFrom-Json)

$swaggerDoc | Add-Member -Name host -MemberType NoteProperty -Value "swagger.io" -Force
$swaggerDoc | Add-Member -Name schemes -MemberType NoteProperty -Value @("https") -Force

$swaggerDoc | ConvertTo-Json | Set-Content $filePath

The problem I have is that the JSON gets completely destroyed when I save it back to the file: For example

  "get": {
    "tags": [
      "Links"
    ],
    "operationId": "Links_GetAll",
    "parameters": [],
    "responses": {
      "200": {
        "description": "Returns all the available links in the system",
        "schema": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/AdministrativeLink"
          }
        },
        "x-nullable": true
      }
    }
  }

becomes

"get":  "@{tags=System.Object[]; operationId=Links_GetAll; parameters=System.Object[]; responses=}",

I haven't seen any other examples on how to do this in Powershell, is there some syntax or parameter I am missing in order to retain the original format?

Upvotes: 6

Views: 1590

Answers (2)

Matt
Matt

Reputation: 1240

When using ConvertTo-Json, use -Depth to retain proper format of the JSON.

For Example:

$swaggerDoc | ConvertTo-Json -Depth 10 | Set-Content $filePath

I also had to add brackets around your JSON to make it valid JSON readable by powershell.

Upvotes: 4

ddlingo
ddlingo

Reputation: 101

If you are cutting and pasting then make sure you remove formatting. For example if you are using a Mac, paste with "Command + Shift + V", this will remove formatting when cutting and pasting. Also never use "TABS" while inside of a JSON file, only "ENTER" and Spaces

Upvotes: 0

Related Questions