While writing a JSON parser in Java I ran into a "cosmetic" problem:
In the JSON specification it's clearly said that Javascript control characters are the same as e.g. in C and Java, like \n or \t. The problem I was running into, is that when there are control codes within a JSON string (so within the quotes: "property":"value"), then the displayed JSON code is messed up because the control characters are changing the print, e.g. \n creates a new line or \t creates a tab.
An example:
String s = "{\n\t\"property1\": \"The quick brown fox\njumps over the lazy dog\",\n\t\"property2\":\"value2\"\n}"
Printing as:
{
"property1": "The quick brown fox
jumps over the lazy dog",
"property2": "value2"
}
The solution would look like this:
String s = "{\n\t\"property1\": \"The quick brown fox\\njumps over the lazy dog\",\n\t\"property2\": \"value2\"\n}"
Printing "correctly" as:
{
"property1": "The quick brown fox\njumps over the lazy dog",
"property2": "value2"
}
So my question: Is it correct to treat control code outside strings differently than the control code within strings? And is it correct to add within JSON strings another backslash \ before any control characters, creating strings like "\n" or "\t" that won't have any effect on the look of JSON strings?