Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through json custom object

I'm trying to perform some config transformations on JSON files using PowerShell. For this there's several input json files and a transform one (one for each environment).

Input sample (AzureStorage.json):

{
"$schema": "http://datafactories.schema.management.azure.com/schemas/2015-09-01/Microsoft.DataFactory.LinkedService.json",
"name": "AzureStorage",
"properties": {
"type": "AzureStorage",
  "typeProperties": {
    "connectionString": "My Connection String here"
  } } }

Transform:

{
  "$schema": "http://datafactories.schema.management.azure.com/vsschemas/V1/Microsoft.DataFactory.Config.json",
  "AzureStorage": [
    {
      "name": "$.properties.typeProperties.connectionString",
      "value": "DefaultEndpointsProtocol=https;AccountName=mytestaccount;AccountKey=d;lasfjdalfdjfldjfdsfds;EndpointSuffix=core.windows.net"
    }
  ],
  "DataLakeStore": [
    {
      "name": "$.properties.typeProperties.dataLakeStoreUri",
      "value": "https://mydatalake.azuredatalakestore.net/webhdfs/v1"
    }
  ]
}

What I need to do, is to load the transform file, then traverse it, finding the names of the input files I need to transform (in this example AzureStorage.json and DataLakeStore.json).

Next, I need to replace the properties accordingly. I'm trying to do it by loading the transform file into a variable using ConvertFrom-Json, but I not sure how to traverse it afterwards.

like image 322
Daniel Perez Avatar asked Nov 24 '25 20:11

Daniel Perez


1 Answers

I don't know hat exactly you need. I'm guessing access to the information within the JSON file.

What about this approach?

$json_object = Get-Content -Raw -Path '<your_path>\transform.json' | ConvertFrom-Json
$azure_storage = @('AzureStorage'; 'DataLakeStore')

ForEach ($azure in $json_object) {
    ForEach ($storage in $azure_storage) {
        Write-Output $azure.$storage.name
        Write-Output $azure.$storage.value
    }
}

Edit Due to edit I got it. You need a generic access.

Here you go:

$json_object = (Get-Content -Path '<your_path>\transform.json') -join "`n"  | ConvertFrom-Json

ForEach ($object in $json_object.PsObject.Properties) {
    Write-Output $object.name
    Write-Output $object.value
}

Explanation: (Get-Content -Path '<your_path>\transform.json') -join "n"` is a Microsoft's MSDN recommended way to read json files.

You need to find out where the values are. The object you are using is a "Windows PowerShell custom object" - PsObject. To access the you need to use .Properties.value. Then you have the Strings you want and you can access them using .name and .value.

like image 197
tukan Avatar answered Nov 27 '25 11:11

tukan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!