Enis Erkaya
Enis Erkaya

Reputation: 81

\n gives error when parsing json in flutter

I have a json array like this:

[
{
"variable1":"example",
"variable2": "example1\nexample2\nexample3"
},
{
"variable1":"exampleLast\n",
"variable2": "example1\nexample2\nexample3"
}
]

I am trying to parse this json a List in Flutter.

List posts = json.decode(response.data);

When I tried using 'dart:convert' it gives error FormatException... Control character in string (at line...).

I found this issue on Github but I can not find solution.
https://github.com/dart-lang/convert/issues/10

Upvotes: 7

Views: 5295

Answers (4)

Valentina Konyukhova
Valentina Konyukhova

Reputation: 5334

Previous answers didn't help me. In the mentioned Github thread there is a good solution: add r to make compiler think that there is no special characters in the line.

final jsonContent = r'''{ "pageNumber": 0, "pageCount": 0, "transactionId": "126cf723-1d57-4f49-8fb2-072b7c23ec1e", "entries": [ { "content": "{\"resourceType\":\"Bundle\",\"id\":\"DRiefcase_2021-03-15__ManjoorKapoor_Pres-13116\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2021-01-20T04:51:59.1497479Z\",\"profile\":[\"https:\\/\\/nrces.in\\/ndhm\\/fhir\\/r4\\/StructureDefinition\\/DocumentBundle\"]}}}]}''';

Upvotes: 4

Arbaz Alam
Arbaz Alam

Reputation: 1382

Just replace the single backslash(\n) with double backslash(\\n) in your code:

[{
    "variable1": "example",
    "variable2": "example1\\nexample2\\nexample3"
},
{
    "variable1": "exampleLast\\n",
    "variable2": "example1\\nexample2\\nexample3"
}]

You need to escape the \ in your string (turning it into a double-), otherwise it will become a newline in the JSON source, not the JSON data.

Upvotes: 3

ramzieus
ramzieus

Reputation: 157

And you can replace it like this

String replaced = string.replaceAll('\n', '\\n');

also check this response

Upvotes: 1

Arjun Vyas
Arjun Vyas

Reputation: 419

You just need to replace single slash to double slash and everything goes fine.

String replaced = string.replaceAll(r'\', r'\\');

Upvotes: 5

Related Questions