0

I have a JSON file with configurations that I use to determine what properties I need to call on an object.

Since PowerShell allows using a string variable as property this works fine like so:

$config = Get-Content .\syncProperties.json -Raw | ConvertFrom-Json
$myPropertyFromJSON = $config.profileMappings[0].sourceField
echo $myObject.$myPropertyFromJSON

however sourceField can be a sub-property like "SomeProperty.SubProperty" and this of course does not work.

What would be a nice generic way to handle properties/sub-properties from JSON (read: I dont want to do some nasty replacing or splitting)

Sample JSON:

{
    "profileMappings": [
        {
            "source": "AzureRm",
            "sourceField": "ExtensionProperty.extension_xyz_countryCode",
            "destinationField": "countryCode"
        },
        {
            "source": "AzureRm",
            "sourceField": "Department",
            "destinationField": "companyName"
        },
        { 
            "source": "EXO",
            "sourceField": "CustomAttribute1",
            "destinationField": "BuildingNo"
        }
    ]
}
iRon
  • 20,463
  • 10
  • 53
  • 79
Anders Rask
  • 862
  • 6
  • 17
  • By happy accident PowerShell also uses the period as an accessor operator, so you may get away with some form of `Invoke-Expression`. You do need to completely trust the JSON you're processing that way, though, because you're running arbitrary code. "Nasty replacing or splitting" is another way of saying "parsing", which is sometimes just necessary. – Jeroen Mostert Sep 25 '17 at 12:31
  • Hmm, any thoughs on how to get & to resolve this? I agree that parsing may be a more robust way, but i generate the JSON myself so it is "trustworthy" ;) – Anders Rask Sep 25 '17 at 13:03
  • 1
    Is the name of SubProperty always the same? Can there be other subproperties? Post a sample JSON. – AdamL Sep 25 '17 at 13:17
  • I am not sure if it answers your question but I wrote a cmdlet [`Flatten-Object`](https://stackoverflow.com/a/46081131/1701026) that basically flattens any sub-property to a main property *named*: `[String]SomeProperty.SubProperty` – iRon Sep 25 '17 at 17:21
  • @AdamLuniewski Sub properties can be any ExtensionProperty.something (added JSON to Q) – Anders Rask Sep 27 '17 at 08:47
  • @iRon not really, as I'm talking about a string that is a sub property, not nested arrays in JSON (see added JSON sample) – Anders Rask Sep 27 '17 at 09:38
  • Still not sure were you exactly looking for but to enumerate all the `sourceField` properties without knowing the main property, you can do something like: `$Config | ForEach {$_.PSObject.Properties.Value | ForEach {$_.SourceField}}` – iRon Sep 27 '17 at 11:34

0 Answers0