Skip to content

Instantly share code, notes, and snippets.

@alexanderankin
Last active October 13, 2023 02:39
Show Gist options
  • Save alexanderankin/1c37af94832f5e533ba2ca79e00eb1fd to your computer and use it in GitHub Desktop.
Save alexanderankin/1c37af94832f5e533ba2ca79e00eb1fd to your computer and use it in GitHub Desktop.
# Read the JSON file into a string
$jsonString = Get-Content -Raw "file.json"
# Convert the JSON string to a PowerShell object
$jsonObject = ConvertFrom-Json $jsonString
# Modify the JSON object as needed
$jsonObject.abc = $true
# Convert the modified object back to a JSON string
$modifiedJsonString = $jsonObject | ConvertTo-Json
# Preserve the comments by including them in the JSON string
$modifiedJsonString = $modifiedJsonString -replace '(?s)(\s*"_comments"\s*:\s*\[)(.*?)(\s*\])', '$1' + ($jsonObject._comments | ForEach-Object { '"'+$_+'"' }) + '$3'
# Save the modified JSON string back to the file
$modifiedJsonString | Set-Content -Path "file.json"
# Display the contents of the modified JSON file
Get-Content "file.json"
# Create an empty JSON object
$jsonObject = New-Object PSObject | ConvertTo-Json
# Set the 'abc' property to 'true'
$jsonObject = $jsonObject | ConvertFrom-Json
$jsonObject.abc = $true
$jsonObject = $jsonObject | ConvertTo-Json
# Save the modified JSON to a file
$jsonObject | Set-Content -Path "file.json"
# Display the contents of the modified JSON file
Get-Content "file.json"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment