Quick tip: ConvertTo-Json and line breaks in strings

The built-in commands to convert to and from JSON is some (of many) great reasons why PowerShell is such a joy to use. In this short blog post I’m going to write about using line breaks in strings together with ConvertTo-Json.

The most used way of doing this is probably something like this:

" | ConvertTo-Json

The output of this command is "item1\nitem2\n". Here you see that PowerShell have converted the line breaks into \n in the resulting string.

Unfortunately, PowerShell being helpful like this can sometimes backfire. Consider the following example:

"item1\nitem2\n" | ConvertTo-Json

There might be several reasons why you would already have the line breaks in the string before you send it to ConvertTo-Json; perhaps it’s dynamically generated or is the output of some other command.

The output of this command though is not correct: "item1\\nitem2\\n". You can’t really fault PowerShell for this behaviour as it’s just trying to help you out by escaping the slash’es in the string, but it might not be the result you are after!

The solution of course, is to alter the command slightly:

("item1\nitem2\n" | ConvertTo-Json).Replace('\\n','\n')

Now you get the correct and expected output "item1\nitem2\n", by replacing all occurrences of \\n with \n.

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s