I get FormatException when decoding the string from an HTTP response. It's because of the \n character in the string. It works when I convert the string a raw string.
It's easy to declare a raw string
String raw = r'Hello \n World';
But how can I convert an existing string to a raw string?
String notRaw = 'Hello \n World';
String raw = r'${notRaw}';
the above statement doesn't work as everything is after r' is treated as raw String.
I'm having two questions
1) How to avoid the \n issue when decoding JSON. 2) How to convert an existing string variable to a raw string.
import 'dart:convert';
void main() {
var jsonRes = """
{
"response-list": {
"response": [
{
"attribute": {
"@name": "Problem",
"@isEditable": false,
"@value": "Services fail to respond; for example:\n\n1) unable to connect.\n2) Slow response on the console.\n3)no response."
}
}
]
}
}
""";
var jsonStr = json.decode(jsonRes);
print (jsonRes);
}
Converting to Raw String
import 'dart:convert';
void main() {
var jsonRes = r"""
{
"response-list": {
"response": [
{
"attribute": {
"@name": "Problem",
"@isEditable": false,
"@value": "Services fail to respond; for example:\n\n1) unable to connect.\n2) Slow response on the console.\n3)no response."
}
}
]
}
}
""";
var jsonStr = json.decode(jsonRes);
print (jsonRes);
}
There is no such thing as converting to a raw string. A raw string is just a Dart syntax construct, not a property of the string. String notRaw = 'Hello \\n World'; to get the same string representation that would get with the raw string syntax.
Python raw string is created by prefixing a string literal with 'r' or 'R'. Python raw string treats backslash (\) as a literal character. This is useful when we want to have a string that contains backslash and don't want it to be treated as an escape character.
In Python, when you prefix a string with the letter r or R such as r'...' and R'...' , that string becomes a raw string. Unlike a regular string, a raw string treats the backslashes ( \ ) as literal characters.
There is no such thing as converting to a raw string. A raw string is just a Dart syntax construct, not a property of the string.
Instead of
String notRaw = 'Hello \n World';
use
String notRaw = 'Hello \\n World';
to get the same string representation that would get with the raw string syntax.
r'xxx'
means take xxx
literally. Without r
\n
will be converted to an actual newline character. When the backslash is escaped like '\\n'
, then this is interpreted as raw '\n'
.
So using raw syntax (r'xxx'
) just spares escaping every \
and $
individually.
See also How do I handle newlines in JSON?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With