2

I am trying to write a PS script with an array for multiple items using ConvertTo-Json. I need this script to use in Azure DevOps pipeline. For example, using variables I could convert multiple items into Json. The script works for a single item as I want, but cannot figure out how to feed multiple items as one variable.

# Variables
$Roles = "Reader"
$Name = "User1"
$Email = "[email protected]"

$UserList = ConvertTo-Json @(@{Roles = @("$Roles"); Name = "$Name"; Email = "$Email"})

# Output for a single item as I need
PS C:\> $UserList
[
    {
        "Email":  "[email protected]",
        "Name":  "User1",
        "Roles":  [
                      "Reader"
                  ]
    }
]

What I need to achieve is to add more items into every single variable, so an output would be as below with two users

[
        {
            "Email":  "[email protected]",
            "Name":  "User1",
            "Roles":  [
                          "Reader"
                      ]
        },
        {
            "Email":  "[email protected]",
            "Name":  "User2",
            "Roles":  [
                          "Reader"
                      ]
        }
] 

I tried to use variables using an array as @("Reader"; "Reader"), but the output is not what I need. Can someone please help to achieve it? Thanks!

1
  • Not sure I'm following, you can just pass an array of users with their mails and roles through the pipeline to ConvertTo-Json to get that desired output. Commented Aug 13, 2021 at 22:23

2 Answers 2

4

If you want objects to be represented in the resulting JSON you should feed objects into the ConvertTo-Json cmdlet. Similar to Sage's fine answer:

$Objects =
@(
    [PSCustomObject]@{
        Name  = "User1"
        Email = "[email protected]"
        Roles = @("Reader")
    }
    [PSCustomObject]@{
        Name  = "User2"
        Email = "[email protected]"
        Roles = @("Reader")
    }
)

$UserList = $Objects | ConvertTo-Json

$UserList

You can also shorten with:

$UserList =
@(
    [PSCustomObject]@{
        Name  = "User1"
        Email = "[email protected]"
        Roles = @("Reader")
    }
    [PSCustomObject]@{
        Name  = "User2"
        Email = "[email protected]"
        Roles = @("Reader")
    }
) | ConvertTo-Json

$UserList

Unless we are misunderstanding the issue, I don't see a reason to store the array elements in discrete variables first. It's an array of objects you want and that will need to be created somewhere. If there is input that goes with your project it might help.

Sign up to request clarification or add additional context in comments.

3 Comments

This is beautiful. Not sure where my head was at but That's the way I would prefer for a static list. I left my answer, since this could prove useful if the data was dynamically obtained, but otherwise, this x 1000
Thanks @Steven for the solution. It definitely helped me to understand better about an array and PSCustomObject. I am still not understanding this, is it possible to create arrays based on dynamic items from variables? For example, as more items in variables are added as more arrays are created using your solution? Thanks in advance for looking at it!
Yes, but I'm not sure I understand the question. The fundamentals of what's shown will work in many scenarios, adjustments may be necessary depending on what those variable were, how they are stated etc.
4

Note: Steven's answer and its code formatting put my answer to shame so you should definitely use the formatting he shows if you have a defined static list that you need to convert to JSON.

That being said, I am leaving my answer for reference, as it might still be useful to know that you can do it through the creation of a PSObject list in the event the number of items you needed to add was dynamically picked up from somewhere.

If that is your scenario, then

  • Creating a PSObject list
  • Appending dynamically all items to it picked up from another source
  • Converting the list to a json object

would be the way to go. For list where you can hardcode the layout of your final json (eg: defined number of items), then his answer x 1000.


Original answer

You can create a list of PSObject, then add your items into it and convert it to json, like so.

$UserListObj = [System.Collections.Generic.List[PSObject]]::new()
$UserListObj.Add(([PSCustomObject]@{Email = "[email protected]"; Name = "User1"; Roles = @("Reader") }))
$UserListObj.Add([PSCustomObject]@{Email = "[email protected]"; Name = 'User 2'; Roles = @('Reader', 'Collaborator') })
$UserList = ConvertTo-Json $UserListObj

Note that you don't thave to do the whole PSCustomObject / Value fill / Add in one line. I like to do it like that when I have very small psobject but you can aerate your code a bit more. A more vertically inclined version of the same thing.

$UserListObj = [System.Collections.Generic.List[PSObject]]::new()

$User1 = [PSCustomObject]@{
        Email = "[email protected]" 
        Name  = "User1"
        Roles = @("Reader") 
    }
$UserListObj.Add($User2)

$User2 = [PSCustomObject]@{
        Email = "[email protected]" 
        Name  = "User 2"
        Roles = @("Reader","Collaborator") 
    }
$UserListObj.Add($User2)

$UserList = ConvertTo-Json $UserListObj

Side note If you need to go deeper than 4 level with your Json, don't forget to add -Depth X parameter with the desired depth. This is because ConvertTo-Json default behavior is to convert an object only up to the fourth depth layer.

2 Comments

Good foresight on the -Depth parameter.
Thanks Sage for your solution as well, it is definitely worth attention. I am going to play with PSObject list and see what I can get :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.