【问题标题】:Dart: Parse JSON with commentsDart:使用注释解析 JSON
【发布时间】:2021-11-08 07:05:58
【问题描述】:

我已经尝试在解析之前将它们过滤掉,但问题是,一个值中可能有“//”、“/*”和“*/”,例如,如果该值是一个链接什么的。

一个例子:

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

【问题讨论】:

    标签: json dart parsing comments


    【解决方案1】:

    从技术上讲,使用RegExp 删除 cmets 是可行的,您只需检测字符串文字,以避免触发字符串内部的 cmets,然后不删除字符串,仅删除 cmets。由于转义,字符串有点棘手,但至少 JSON 只使用一种引号。

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

    我假设没有 nested cmets,因为这会使检测它们变得非常规。

    【讨论】:

      【解决方案2】:

      还有JSON5 支持单行和多行cmets。看起来 pub.dev 上的 json5 包是您正在寻找的。 :)

      这是一个如何使用它的示例:

      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);
      }
      

      【讨论】:

      • 这有点适合我,唯一的问题是它无法解析任何“\r\n”。我解决这个问题的方法是,我首先将所有“\r\n”替换为“endl”,然后将其替换回“\r\n”。但是,此解决方案可能会在将来引起问题。要知道,我将保持原样并在 GitHub 上的 JSON5 包中打开一个问题,并希望它得到解决。不过谢谢!
      猜你喜欢
      • 2020-11-25
      • 1970-01-01
      • 2011-03-24
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-22
      • 2020-02-14
      相关资源
      最近更新 更多