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:
[code language=“javascript”]
{“people”: [ { “name”: “John Smith”, “city”: “London”, “country”: “United Kingdom”, “age”: 27 }, { “name”: “George Burns”, “city”: “New York”, “country”: “USA”, “age”: 32 } ] }
[/code]
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
However, if there is a syntax error in the JSON text then I will get something like this:
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:
and if we look at the text I gave I missed out a " at the end of “city”: “London,
[code language=“javascript”]
{“people”: [ { “name”: “John Smith”, “city”: “London, “country”: “United Kingdom”, “age”: 27 }, { “name”: “George Burns”, “city”: “New York”, “country”: “USA”, “age”: 32 } ] }
[/code]