skip to Main Content

Trying to add new location to this json file, after adding entire json file is out of format and there’s tons of extra spaces added. how to deal this.

{
  "$schema": "https://schema.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "existingGalleryName": {
      "value": "Gallery"
    },
    "serviceArtifactName": {
      "value": "servicename"
    },
    "location": {
      "value": "East US"
    },
    "targetLocations": {
      "value": [
        {
          "name": "Qatar Central"
        },
        {
          "name": "Central US EUAP"
        },
        {
          "name": "East US 2 EUAP"
        },
        {
          "name": "West Central US"
        }
      ]
    },
    "description": {
      "value": "Redis Service Artifact for Standard Customers without scheduled patch window"
    }
  }
}

Trying to add new name field

{
   "name": "Australia"
}

expected

 "parameters": {
    "existingGalleryName": {
      "value": "Gallery"
    },
    "serviceArtifactName": {
      "value": "servicename"
    },
    "location": {
      "value": "East US"
    },
    "targetLocations": {
      "value": [
        {
          "name": "Qatar Central"
        },
        {
          "name": "Central US EUAP"
        },
        {
          "name": "East US 2 EUAP"
        },
        {
          "name": "West Central US"
        },
        {
          "name": "Australia"
        }
      ]
    },
    "description": {
      "value": "Redis Service Artifact for Standard Customers without scheduled patch window"
    }
  }
}

MyOutput:

{
    "$schema":  "https://schema.json#",
    "contentVersion":  "1.0.0.0",
    "parameters":  {
                       "existingGalleryName":  {
                                                   "value":  "Gallery"
                                               },
                       "serviceArtifactName":  {
                                                   "value":  "servicename"
                                               },
                       "location":  {
                                        "value":  "East US"
                                    },
                       "targetLocations":  {
                                               "value":  [
                                                             {
                                                                 "name":  "Qatar Central"
                                                             },
                                                             {
                                                                 "name":  "Central US EUAP"
                                                             },
                                                             {
                                                                 "name":  "East US 2 EUAP"
                                                             },
                                                             {
                                                                 "name":  "West Central US"
                                                             },
                                                             {
                                                                 "name":  "australia"
                                                             }
                                                         ]
                                           },
                       "description":  {
                                           "value":  "Redis Service Artifact for Standard Customers without scheduled patch window"
                                       }
                   }
}

MyCode:

function ServiceArtifact {
    param (
        [string]$jsonFilePath,
        [string]$newLocationName
    )

    # Read the JSON file content and convert it to a PowerShell object
    $jsonContent = Get-Content -Path $jsonFilePath -Raw | ConvertFrom-Json

    # Define the new location to be added
    $newLocationjson = @{
        name = "$newLocationName"
    }

    # Add the new location to the targetLocations array
    $jsonContent.parameters.targetLocations.value += $newLocationjson

    # Convert the updated content back to JSON format
    $updatedJsonContent = $jsonContent | ConvertTo-Json -Depth 10

    # Write the updated JSON content back to the file
    $updatedJsonContent | Set-Content -Path $jsonFilePath
    
    Write-Output "New location '$newLocationName' added successfully."
}

# Automatically determine the path of the JSON file within the cloned repository
$filePath = "E:vagrant-vmstemparea.json"
$newLocationName = Read-Host "Enter the location that you want to add"

# Usage
ServiceArtifact -jsonFilePath $filePath -newLocationName $newLocationName

This code reads the json from a file and input from cmd.

the input is added to the json file,

The main problem here is when input is added to json file, the entire json format is getting distrubed.

How can I solve this ?

2

Answers


  1. The ConvertFrom-Json converts json-object literals to PSCustomObjects objects. This is the standard behavior in Windows PowerShell and optional in PowerShell 7 where you might convert json-objects to a HashTable (or rather a case-insensitive OrderedHashtable) using the -AsHashTable switch.
    Besides, Json-Array literals are converted to fixed arrays (related propose: #24010 Add -AsList switch to ConvertFrom-Json) which requires to use the ineffective assignment operator (+=) to add an item. For more information see: Why should I avoid using the increase assignment operator (+=) to create a collection and the addendum from Santiago-Squarzon about the upcomming PowerShell improvement).

    To overcome a few of these obstacles, I am creating an ObjectGraphTools module, that:

    • handles any PSCustomObject similar as any dictionary collection.
    • lets you easily copy and convert (see Copy-ObjectGraph) between:
      • an array and any list collection
      • PSCustomObjects and any dictionary collection
    • Easially address nodes
    • Several other features (that are unrelated to this post)

    Specific to your question:

    Install-Module -Name ObjectGraphTools
    
    $Schema = $jsonContent | Copy-ObjectGraph -ListAs List[Object]
    $Values = $Schema | Get-Node 'parameters.targetlocations.Value'
    $Values.Value.Add(@{ name = "Australia" }) # --> $Values.Add(...), see: https://github.com/iRon7/ObjectGraphTools/issues/98
    $Values.RootNode.Value | ConvertTo-Json -Depth 9
    
    {
      "$schema": "https://schema.json#",
      "contentVersion": "1.0.0.0",
      "parameters": {
        "existingGalleryName": {
          "value": "Gallery"
        },
        "serviceArtifactName": {
          "value": "servicename"
        },
        "location": {
          "value": "East US"
        },
        "targetLocations": {
          "value": [
            {
              "name": "Qatar Central"
            },
            {
              "name": "Central US EUAP"
            },
            {
              "name": "East US 2 EUAP"
            },
            {
              "name": "West Central US"
            },
            {
              "name": "Australia"
            }
          ]
        },
        "description": {
          "value": "Redis Service Artifact for Standard Customers without scheduled patch window"
        }
      }
    }
    
    Login or Signup to reply.
  2. Json formating using powershell
    In PowerShell, you can work with JSON data using the ConvertTo-Json and ConvertFrom-Json cmdlets. Here’s how you can format data as JSON:

    1. Convert a PowerShell object to JSON If you have a PowerShell object and want to convert it to JSON, use ConvertTo-Json.
    $jsonString = '{
        "Name": "John Doe",
        "Age": 30,
        "Occupation": "Engineer",
        "Skills": ["PowerShell", "C#", "SQL"]
    }'
    
    $object = $jsonString | ConvertFrom-Json
    Write-Output $object

    -Depth: Specifies the number of levels to include in the JSON string. The default value is 2. If your data has more nested levels, you can increase the depth accordingly.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search