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.


  1. “item1\nitem2\n” is not a PowerShell representation of a string with new lines. So it would seem, that you have the text already partially in Json/JavaScript format (or similar, e.g. C++, C#). PowerShell is behaving correctly here. You would rather be better “fixing” the string before you pass it to conversion to Json. Using “$input.Replace(‘\n’, “`n”) | ConvertTo-Json” is probably a bit too simple (as it does not cover all uses of backslash, e.g. not correctly handle cases where you have a backslash represented with an “n” character afterwards, i.e. “k\\l\\m\\n\\o\\p” represents “k\l\m\n\o\p”, but would be incorrectly treated as if it contained a new line).
    All in all, the key point would be understanding the format of the string you have (e.g. C# string literals) and applying its syntax (converting a C# string literal to a string value).
    If the problem is from you copy-pasting strings from some code (or extracting from some Json files), then you should stop. 🙂


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 )

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