Home > Net >  Iterate through a text file and add entries to the JSON using powershell
Iterate through a text file and add entries to the JSON using powershell

Time:10-11

I have a text file with below data which is Dynamically generated, so the contents of the repo.txt keep changing

  repo.txt -> Content as below
    repo1
    repo2
    repo_3

And a JSON file

  template.json -> Content as below
  {

  "name": "new-report-test-1",
  "resources": {
    "repositories": [
      {
        "name": "repoa"
      },
      {
        "name": "repo_b"
      }
    ]
  },
    "filters": {
      "severities": [
        "High"
      ]
    }

  }

now i want to read the repo list from the repo.txt file and update the template.json to below


{

  "name": "new-report-test-1",
  "resources": {
    "repositories": [
     {
        "name": "repoa"
      },
      {
        "name": "repo_b"
      },
      {
        "name": "repo1"
      },
       {
        "name": "repo2"
      },
       {
        "name": "repo_3"
      }   
    ]
  },
    "filters": {
      "severities": [
        "High",
        "Medium",
        "Critical"
      ]
    }

  }
 

I have this bash script that does the job thiugh I'm unsure how to translate it to PoweShell. Any inputs would be highly appreciated

cat ./tmpgen_reponames.txt | while read repoEntry do echo " Repository: $repoEntry" cat <<< $(jq --arg REPOID "$repoEntry" '[ .[] , {"name":$REPOID} ]' tmpgen_repoarray.json) > tmpgen_repoarray.json done

CodePudding user response:

You can accomplish this in PowerShell using ConvertFrom-Json to convert your Json into objects then following an object-oriented approach adding new custom objects to the .resources.repositories property and adding the new values Medium and Critical to the .filters.severities property of your Json, lastly, converting it back to a Json string with ConvertTo-Json:

$json = Get-Content path\to\template.json -Raw | ConvertFrom-Json
$json.resources.repositories = @(
    $json.resources.repositories
    (Get-Content path\to\repo.txt).Trim() | ForEach-Object {
        [pscustomobject]@{ Name = $_ }
    }
)
$json.filters.severities = @(
    $json.filters.severities
    'Medium'
    'Critical'
)
$json | ConvertTo-Json -Depth 99 | Set-Content path\to\newJson.Json
  • Related