Convert Unquoted JSON Using Dart

Viewed 16

I am getting unquoted JSON from a trusted 3rd party that looks like this:

{id: 2, name: Test Testerson, course_progress: 0, last_activity_date: null}, {id: 3, name: Poghos Adamyan, course_progress: 0, last_activity_date: null}

What is the best way using Dart for me to format this into valid JSON for use?

1 Answers

If you're absolutely certain that your response is that verbatim string and that you haven't already decoded it, then you would have to parse it manually and hope that there will never be ambiguity. If the data always follows a strict format and if all fields are always in a specific order, you could write a regular expression to parse it. For example:

void main() {
  var s =
      '{id: 2, name: Test Testerson, course_progress: 0, last_activity_date: null}, {id: 3, name: Poghos Adamyan, course_progress: 0, last_activity_date: null}';
  var re = RegExp(
    r'\{'
    r'id: (?<id>\d+), '
    r'name: (?<name>[^,]+), '
    r'course_progress: (?<progress>\d+), '
    r'last_activity_date: (?<last>[^}]+)'
    r'\}',
  );
  var matches = re.allMatches(s);

  var items = <Map<String, dynamic>>[
    for (var match in matches)
      <String, dynamic>{
        'id': int.parse(match.namedGroup('id')!),
        'name': match.namedGroup('name')!,
        'course_progress': int.parse(match.namedGroup('progress')!),
        'last_activity': DateTime.tryParse(match.namedGroup('last')!),
      }
  ];

  items.forEach(print);
}
Related