Home > Net >  Replace Values in a JSON file
Replace Values in a JSON file

Time:10-13

I am new to PowerShell. I have three files output1.txt, output2.txt, deployer.json

output1.txt

db-tenant.rds.amazonaws.com

output2.txt

dev-51-db-global.rds.amazonaws.com

deployer.json

{
"user":"some_user",
"url":"some_url"
"urlglobal":"some_global_url",
"db":"some_db"
}

Desired Output

{
"user":"some_user",
"url":"db-tenant.rds.amazonaws.com"
"urlglobal":"dev-51-db-global.rds.amazonaws.com",
"db":"some_db"
}

I want to get the result from output1.txt and replace the value in url in the deployer.json file

I also want to get the result from output2.txt and replace it with the value in urlglobal in the deployer.json file

Here is a script I started with

script.ps1

$templatecontent = Get-Content -Path .\deployer.json

CodePudding user response:

This is quite simple, hopefully the code is self-explanatory.

$json = Get-Content path\to\deployer.json | ConvertFrom-Json

$json.url = Get-Content 'path\to\output1.txt'
$json.urlglobal = Get-Content 'path\to\output2.txt'

If you want to test the code without using external files:

$url = 'db-tenant.rds.amazonaws.com'
$urlglobal = 'dev-51-db-global.rds.amazonaws.com'

$json = @'
{
"user":"some_user",
"url":"some_url",
"urlglobal":"some_global_url",
"db":"some_db"
}
'@ | ConvertFrom-Json

$json.url = $url
$json.urlglobal = $urlglobal

Then $json | ConvertTo-Json outputs:

{
    "user":  "some_user",
    "url":  "db-tenant.rds.amazonaws.com",
    "urlglobal":  "dev-51-db-global.rds.amazonaws.com",
    "db":  "some_db"
}
  • Related