5

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

Jannie Theunissen
  • 25,269
  • 20
  • 97
  • 121
Enis Erkaya
  • 51
  • 2
  • 5

4 Answers4

2

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

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

Arjun Vyas
  • 390
  • 3
  • 13
2

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.

Arbaz Alam
  • 1,102
  • 14
  • 23
1

And you can replace it like this

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

also check this response

ramzieus
  • 115
  • 10
0

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\"]}}}]}''';
Valentina Konyukhova
  • 3,479
  • 2
  • 21
  • 33