Skip to content

Instantly share code, notes, and snippets.

@JoeCodeswell
Last active October 5, 2020 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoeCodeswell/a565c505e8244bf9105048e874a6adc8 to your computer and use it in GitHub Desktop.
Save JoeCodeswell/a565c505e8244bf9105048e874a6adc8 to your computer and use it in GitHub Desktop.
dart problem typicode jsonDecode with \n
/// zoldCode\dartTypicodeJsonDecodeProblem.dart
/// https://gist.github.com/JoeCodeswell/a565c505e8244bf9105048e874a6adc8
/// https://dartpad.dev/a565c505e8244bf9105048e874a6adc8
///
/// dart fails to jsonDecode valid json string from typicode Posts with \n in it
/// https://github.com/dart-lang/convert/issues/10
///
/// to see non error behaviour comment out lines 29 & 30
///
///
/// See VERY HELPFUL ANSWERS IN [Mapping JSON into Class Objects](https://stackoverflow.com/a/45189401/601770)
import 'dart:convert';
import 'dart:convert';
void main() {
String jsonStrTypicodePostCopiedFromChrome = '''
{
"posts": [
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
]
}'''; // Valid JSON on https://jsonlint.com/
var postObjsJson = jsonDecode(jsonStrTypicodePostCopiedFromChrome)['posts'] as List;
print(postObjsJson);
/* Run time error output
Uncaught Error: FormatException: SyntaxError: Unexpected token
in JSON at position 169
*/
var postObjsJson2 = jsonDecode(jsonStrTypicodePostCopiedFromChrome.replaceAll('\n',' '))['posts'] as List;
print(postObjsJson2);
/* output
[{userId: 1, id: 1, title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit, body: quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto}]
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment