2

I am trying to add value in key pair json file using Powershell. I am getting an error. Need some guidance on PS Scripting.

Powershell 5.1 version and json file with key pair inside it.

MYJSON File:

  {   "Theme":{"Res_List":  {
                    "Method":  "POST",
                     "Name":""}}}

PowerShell Script:


$file_path="C:\Users\RelativeConfig.json"

$json = Get-Content $file_path | Out-String | ConvertFrom-Json

$timestamp = Get-Date -Format ddMMHHmm

$namevalue = 'resource'+$timestamp+'e3'
echo $namevalue ##prints resource16sep2019 I want this to write in json as value for Name Key
$files = $json | Get-Member -MemberType Properties | Select-Object - ExpandProperty Name

$result = Foreach ($file in $json)
{
    if ($file.Name -eq "Name") { $file.Value = $namevalue}
}
$result | ConvertTo-Json | Set-Content $json                                         

Error:

No error but json is not updated with new values.

Expected:

{   "Theme":{"Res_List":  {
                    "Method":  "POST",
                     "Name":"resource16sep2019 "}}}

Actual:

  {   "Theme":{"Res_List":  {
                    "Method":  "POST",
                     "Name":""}}}
2
  • you also want to update the json file? Commented Sep 16, 2019 at 8:49
  • yes my task was to update the json file with the value. Commented Sep 16, 2019 at 10:02

1 Answer 1

2

To update your value in json you can do something like below

$bucket_name = "resource16sep2019"    ## I want this to write in json as value for Name Key

$json.Theme.Res_List.Name = $bucket_name

It will directly replace the $bucket_name value with the Name value in JSON.

If you want to write this to the respective file use the below command,

$json | ConvertTo-Json -depth 32| set-content $file_path

Hope it helps! Cheers

Sign up to request clarification or add additional context in comments.

4 Comments

it is not updating json file.
Thanks! but What happens is it replaces the complete json and writes only the name in json file. I need to use if condition to check if row.key -eq "Name" then add output in value. I am trying many options but in vain.
It doesn't replace the complete JSON in your file. It will replace as "{ "Theme":{"Res_List": { "Method": "POST", "Name":"resource16sep2019 "}}}"
No ng-suhas, it is replacing completely,I am trying other options as well.Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.