0

I have a Array JSON File and i want to set variables corresponding to each key value pair in the JSON

Sample JSON

{
  "rel": "true",
  "test": "true",
  "artifact": "protfolio",
  "build": [
    {
      "appkey": "azure",
      "build_language": "dotnet",
      "script": "",
      "file": "",
      "test_script": ""
    },
    {
      "appkey": "npm",
      "build_language": "dotnet",
      "script": "",
      "file": "",
      "test_script": ""
    }
  ]
}

Now i want to set the variables as below iterating through the JSON

 Name                            Value
$rel                            true
$test                           true
$artifact                       portfolio
$build_appkey_azure             azure
$build_buildlanguage_azure      dotnet
$build_script_azure
$build_file_azure
$build_testscript_azure 
$build_appkey_npm               npm
$build_buildlanguage_npm        dotnet
$build_script_npm
$build_file_npm
$build_testscript_npm

I am able to set the non array elements but not sure how to set the array variables in the way i want, any help would be appreciated

 $json_path =  Get-ChildItem "test.json" -recurse  | %{$_.FullName}
 $json = Get-Content  $json_path -Raw | ConvertFrom-Json
 $json.psobject.properties| Foreach { $hashtable[$_.Name] = $_.Value }
 #echo $hashtable


$hashtable.GetEnumerator() | Sort key | ForEach-Object {

 

$jsonKey = $_.Key
$jsonValue = $_.Value
$Basetype = $jsonValue.GetType() | Select-Object BaseType
 if ( $Basetype.BaseType.Name -eq "Array") {
    $val = $hashtable.Get_Item($jsonKey)
    #echo $val
    echo $val.appkey 
    echo $val.build_language

    #New-Variable -name $($val.name) -value $($val.value) -Force
 }
 else{
   New-Variable -name $jsonKey -value $jsonValue -Force
 }
}
wehelpdox
  • 339
  • 6
  • 16
  • After you ConvertFrom-Json you can just loop on "build" array items and create a var for each property. – JPBlanc Apr 20 '23 at 04:54
  • As a best practice, [don't use the `-Variable` cmdlets for dynamic variable names!](https://stackoverflow.com/a/68830451/1701026). In your case, you might use the [`ConvertFrom-Json -AsHashTable`](https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/convertfrom-json#-ashashtable) parameter and simply address the properties as: `$json.build.appkey_azure`. – iRon Apr 20 '23 at 05:48
  • the array elements are dynamic , so i cannot know if it would be build.appkey_azure or build.posttest_val etc.. and i am using powershell 5.1 so -AsHashTable is not available – wehelpdox Apr 20 '23 at 15:49

0 Answers0