Dart: Parse JSON with comments

Viewed 155

I already tried to filter them out before parsing, but the Problem is, that it is possible to have "//", "/*" and "*/" inside a value, for example if the value is a link or something.

An example:

{
     /*
          this is an explanation for something
     */
     "linkToSomething": "https://something.net" // this is a link to something
     
}
2 Answers

There's also JSON5 which supports single and multi-line comments. Looks like the json5 package on pub.dev is what you're looking for. :)

Here's an example on how to use it:

import 'dart:io';
import 'package:json5/json5.dart';

void main(List<String> arguments) async {
  // Read the file which contains the JSON.
  final value = await File('<file>').readAsString();
  
  // Parse it using the json5 package instead of dart:convert.
  final parsed = json5Decode(value);
}

It's technically possible to remove comments using a RegExp, you just have to detect string literals too, to avoid triggering on comments inside strings, and then not remove the strings, only the comments. Strings are slightly tricky because of escapes, but at least JSON only uses one kind of quote.

var commentRE = RegExp(r'"(?:[^\\"]|\\[^])*"|/\*[^]*?\*/|//.*');
String removeComments(String jsonWithComments) => 
   jsonWithComments.replaceAllMapped(commentRE, (m) {
      var s = m[0]!;
      return s.startsWith('"') ? s : "";
   });

I'm assuming no nested comments because that makes detecting them non-regular.

Related