Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

\n gives error when parsing json in flutter

Tags:

json

flutter

dart

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

like image 668
Enis Erkaya Avatar asked Apr 19 '19 06:04

Enis Erkaya


People also ask

How do you go on receiving JSON array in Flutter and parsing it?

You can do the following: String receivedJson = "... Your JSON string ...."; List<dynamic> list = json. decode(receivedJson); Fact fact = Fact.

How do I parse JSON without casting?

The deep_pick package simplifies JSON parsing with a type-safe API. Once installed, we can use it to get the value we want without manual casts: deep_pick offers a variety of flexible APIs that we can use to parse primitive types, lists, maps, DateTime objects, and more.

How do I parse a JSON string in Dart?

Dart has built in support for parsing json. Given a String you can use the dart:convert library and convert the Json (if valid json) to a Map with string keys and dynamic objects. You can parse json directly and use the map or you can parse it and put it into a typed object so that your data has more structure and it's easier to maintain.

How to parse JSON data from a map?

You can parse json directly and use the map or you can parse it and put it into a typed object so that your data has more structure and it's easier to maintain. So the way you access your parsed data is by using key index on the returned map.

Should I parse large JSON data in an isolate?

And if you need to parse large JSON data, you should do so in a separate isolate for best performance. This article covers all the details: I launched a brand new course where you will learn about state management, app architecture, navigation, testing, and much more:


2 Answers

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

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

like image 165
Arjun Vyas Avatar answered Oct 11 '22 07:10

Arjun Vyas


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.

like image 41
Arbaz Alam Avatar answered Oct 11 '22 08:10

Arbaz Alam