PowerShell Quick Tip: Testing JSON Syntax

I’ve been working a lot with JSON files recently and quite regularly I need to update their content for testing of code changes. While editing the files I want to make sure I don’t introduce an error by making a syntax error in the JSON file. I’ve been using a quick way in PowerShell to test the JSON is clean and if not, to point me at the line in the file where there is a problem.

Take the following example JSON:

{"people": [
{
"name": "John Smith",
"city": "London",
"country": "United Kingdom",
"age": 27
},
{
"name": "George Burns",
"city": "New York",
"country": "USA",
"age": 32
}
] }

I can check this in PowerShell by creating a Here-String of the JSON, then using the ConvertFrom-JSON cmdlet.

$text = @"
{"people": [
{
"name": "John Smith",
"city": "London",
"country": "United Kingdom",
"age": 27
},
{
"name": "George Burns",
"city": "New York",
"country": "USA",
"age": 32
}
] }
"@

$json = $text | ConvertFrom-Json

If there are no issues then I get no errors back and additionally can examine the $json variable to check the contents:

$json.people

JSON01

However, if there is a syntax error in the JSON text then I will get something like this:

JSON02

This line:

ConvertFrom-Json : Invalid object passed in, ‘:’ or ‘}’ expected. (88): {“people”: [

gives us a number, 88, of the character in the string where there is a problem. To head straight to the problem area use:

$text.substring(88)

This will show us text after the error:

JSON03

and if we look at the text I gave I missed out a ” at the end of “city”: “London, 

{"people": [
{
"name": "John Smith",
"city": "London,
"country": "United Kingdom",
"age": 27
},
{
"name": "George Burns",
"city": "New York",
"country": "USA",
"age": 32
}
] }

 

2 thoughts on “PowerShell Quick Tip: Testing JSON Syntax

  1. Perfect, I found with azure ARM templates that convertfrom-json cannot handle comments in the file (/* like this*/). Thanks for this.

Leave a Reply

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