Updating a JSON file without destroying the JSON format

I am 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 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 is that JSON is completely destroyed when I save it back to a 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 have not seen other examples of how to do this in Powershell, is there any syntax or parameter that I am missing to keep the original format?

+4
source share
2 answers

When using, ConvertTo-Jsonuse -Depthto save the correct format JSON.

Example:

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

JSON, JSON, powershell.

+3

, , . , Mac, "Command + Shift + V", . "", JSON, "ENTER"

0

Source: https://habr.com/ru/post/1667066/


All Articles