Converting a Datarow to a JSON object with PowerShell

This is just a quick post. As is frequent with these they are as much for me to refer to in the future and also because the very act of writing it down will aid me in remembering. I encourage you to do the same. Share what you learn because it will help you as well as helping others.

Anyway, I was writing some Pester tests for a module that I was writing when I needed some sample data. I have written before about using Json for this purpose This function required some data from a database so I wrote the query to get the data and used dbatools to run the query against the database using Get-DbaDatabase

Simple enough. I wanted to be able to Mock $variable. I wrapped the code above in a function, let’s call it Run-Query

Which meant that I could easily separate it for mocking in my test. I ran the code and investigated the $variable variable to ensure it had what I wanted for my test and then decided to convert it into JSON using ConvertTo-Json

Lets show what happens with an example using WideWorldImporters and a query I found on Kendra Littles blogpost about deadlocks

If I investigate the $variable variable I get

data results

The results were just what I wanted so I thought I will just convert them to JSON and save them in a file and bingo I have some test data in a mock to ensure my code is doing what I expect. However, when I run

I get

json error.png

and thats just for one row!

The way to resolve this is to only select the data that we need. The easiest way to do this is to exclude the properties that we don’t need

which gave me what I needed and a good use case for -ExcludeProperty

json fixed.png

3 thoughts on “Converting a Datarow to a JSON object with PowerShell

  1. Pingback: DataRow To JSON With Powershell – Curated SQL

  2. Hi Rob,
    wouldn’t it be even easier to let SQL Server do the dirty work, using something like the “FOR JSON” clause…?

    • For the json part yes but it wouldnt make it any easier for PowerShell as it would then have to convert from a datarow (see my datarow conversion post 🙂 )

Please feel free to comment on this post. All comments are moderated first before appearing on the site