1

I have this JSON "Test.json"

      "a": {
        "b": {
          "c": "haha",
          "d": "hoho"
        },
        "c": {
          "a": "blabla"
        }
      }
    }

I have a config file where I save the JSON path in the above JSON in FileConfig.path

    {
       "FileName": "Test.json",
       "FileType": "JSON",
       "FileConfig": [
          {
             "node": "URl",
             "path": "a.b.c",
             "value": "v1"
          },
          {
             "node": "Redirect",
             "path": "a.b.d",
             "value": "V2"
          },
          {
             "node": "Server",
             "path": "a.c.a",
             "value": "V3"
          }
       ]
    }

I want to change the value from the first json using powershell. Running this code works

    $a = Get-Content $pathToJson | ConvertFrom-Json
    $a.a.b.c = "haha"
    $a.a.b.d = "hoho"
    $a.a.c.a = "blabla"
    $a | ConvertTo-Json | set-content $pathToJson  

However, I want to dynamically read the path from my second json which is FileConfig.path . I tried running this code but it doesn't work

 $TagName = $FileConfig.path 
$pathToJson = Join-Path "C:\x\y\z" "Test.json"
    $a = Get-Content $pathToJson | ConvertFrom-Json
    $a.$TagName = "haha"
   
    $a | ConvertTo-Json | set-content $pathToJson  

Any ideas? I just want to be able to dynamically loop through multiple paths set in a config and update a JSON file

  • Maybe this answer can help: [https://stackoverflow.com/questions/33520699/iterating-through-a-json-file-powershell](https://stackoverflow.com/questions/33520699/iterating-through-a-json-file-powershell) – Juanma Feliu Mar 23 '21 at 22:01
  • In short: There is no _built-in_ syntax for nested property access based on a _string_ containing a property _path_, but there are workarounds: see [this answer](https://stackoverflow.com/a/51863728/45375) to the linked duplicate. – mklement0 Mar 23 '21 at 22:58

0 Answers0