If you JSON-decode material containing a value that contains a backslashed "n" to indicate a newline, at what point should you replace it with a true newline?
Here's an artificial example:
let dict = ["key": "value\\nvalue"]
let json = try! JSONEncoder().encode(dict)
let result = try! JSONDecoder().decode([String:String].self, from: json)
print(result["key"])
That outputs "value\\nvalue"
, but for purposes of display in my app, I then call replacingOccurrences
to change "\\n"
(meaning backslashed n" into "\n"
(meaning newline) so that an actual newline appears in my interface.
Now, I'm a little surprised that JSONDecoder isn't already doing this for me. Just as it has a configurable policy for decoding a date string value into a date, I would expect it at the least to have a configurable policy for decoding a string value into a string. But it doesn't.
My question is: what do people do about this sort of situation, as a general rule? Dealing with it on a case by case basis, as I'm doing in my app, feels wrong; in reality, these JSON data are coming from the server and I want all JSON HTTP response bodies to be treated in this way.