Powershell Specific Json Value

Viewed 30

I have a json that I wanted to generate using Powershell

{

"CreatedBy": "div",

"Label": "jss key",

"Scopes": ["content-#everything#", "audience-delivery"]

}

I am using the below to generate the json but it is not successful

$EdgeClientID = 'fsfsdfSDFsda'

$scope = '[ "content-#everything#", "audience-delivery" ]'

$body = @{

    'CreatedBy'     = $EdgeClientID

    'Label' = 'jss key'

    'Scopes'    = $scope

} | ConvertTo-Json

the result I am getting is

{

    "CreatedBy":  "fsfsdfSDFsda",

    "Label":  "jss key",

    "Scopes":  "[\"content-#everything#\", \"audience-delivery\"]"

}

The value of scope is not coming right. Can someone please help?

1 Answers

The reason why you're not getting the desired output from it is because the following is an array only in the context of JSON and not in the context of PowerShell and ConvertTo-Json interprets it a simple string:

$scope = '[ "content-#everything#", "audience-delivery" ]'

The following should fix the problem:

$EdgeClientID = 'fsfsdfSDFsda'
$scope = "content-#everything#", "audience-delivery"
$body = @{
    'CreatedBy' = $EdgeClientID
    'Label'     = 'jss key'
    'Scopes'    = $scope
} | ConvertTo-Json

You could also create a blue print class for your JSON:

class JSONBluePrint {
    [string]$CreatedBy
    [string]$Label
    [object[]]$Scopes

    JSONBluePrint () { }
    JSONBluePrint([string]$CreatedBy, [string]$Label, [object[]]$Scopes)
    {
        $this.CreatedBy = $CreatedBy
        $this.Label = $Label
        $this.Scopes = $Scopes
    }

    [string] ToJson () {
        return $this | ConvertTo-Json -Depth 100
    }
}

[JSONBluePrint]::new(
    'div',
    'jss key',
    @('content-#everything#', 'audience-delivery')
).ToJson()

$json = [JSONBluePrint]::new()
$json.CreatedBy = 'div'
$json.Label = 'jss key'
$json.Scopes = 'content-#everything#', 'audience-delivery'
$json.ToJson()
Related