AL Extensions: Reading JSON info with Powershell

A quick post today on how to read values from a JSON file with PowerShell.
PowerShell contains the commandlet ConvertFrom-Json, which as its name implies, converts a JSON object into a PowerShell object, from which you can then access the values and read them into variables, etc.
Let’s assume we have a file named MyFile.json, which contains the following JSON object:

{
   "id": "123456",
   "name": "MyObjectName"
}

We can convert this into a PowerShell object with the following code:

$JsonObject = Get-Content -Raw -Path .\MyFile.json | ConvertFrom-Json

We can then read the value of  name into a variable like this:

$Name = $JsonObject.Name

SO WHAT?

As the title of this post suggests, we can make use of this handy code with our AL extensions.
In my previous post, I showed you how to create a custom AL extension build task with Visual Studio Code. You can expand on this and launch a PowerShell script to execute the ALC compiler. When you do that, one of the parameters you can supply to the compiler is the output path and resulting app file name. By using the app.json file that is part of every AL extension, you can utilize things such as the extension publisher, name, version, etc. in your compiler process.
You can do something like the following…

$JsonObject = Get-Content -Raw -Path .\app.json | ConvertFrom-Json
$ExtensionName = $JsonObject.Publisher + '_' + $JsonObject.Name + '_' + $JsonObject.Version + '.app'
$CompilerPath = 'C:\Users\<username>\.vscode\extensions\Microsoft.al-0.10.13928\bin'
$ALProjectFolder = 'C:\MyProjectFolder'
$ALPackageCachePath = Join-Path -Path $ALProjectFolder -ChildPath '.alPackages'
$AlPackageOutFilePath = Join-Path -Path 'C:\MyCustomOutputFolder' -ChildPath $ExtensionName
Set-Location -Path $CompilerPath
.\alc.exe /project:$ALProjectFolder /packagecachepath:$ALPackageCachePath /out:$AlPackageOutFilePath

…which would replicate the same file name that the out of box compile process does, but will still allow you to direct the file to be output to a custom path. For example, maybe a shared AL package cache that you use for multiple developers.
Until next time, happy coding!

1 Comment

  1. Good information. Lucky me I ran across your website by accident (stumbleupon). I have saved it for later!|

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

© 2019 NAV Bits and Bytes

Theme by Anders NorénUp ↑