【问题标题】:Read JSON with embedded JS comments using Jackson使用 Jackson 读取带有嵌入式 JS 注释的 JSON
【发布时间】:2021-06-29 01:07:53
【问题描述】:

我正在寻找一种处理 JSON 的方法,其中包括 JS cmets。我知道,cmets 对于 JSON 是不合法的,但不幸的是,我需要使用 cmets 读取/写入 JSON 文件。

我找到了一种使用 Jackson 编写 cmets 的方法。本代码

JsonGenerator gen = factory.createGenerator(System.out);
gen.writeStartObject();
gen.writeStringField("a", "b");
gen.writeRaw("\n/*------------*/\n");
gen.writeStringField("c", "d");
gen.writeEndObject();
gen.close();

生成以下 JSON:

{"a":"b"
/*------------*/
,"c":"d"}

如果我开始解析这个 JSON

factory.enable(JsonParser.Feature.ALLOW_COMMENTS);
JsonParser parser = factory.createParser("{\"a\":\"b\"/*------------*/,\"c\":\"d\"}");
while (parser.nextToken() != JsonToken.END_OBJECT) {
    System.out.println(parser.currentToken() + ":" + parser.getText());
}

cmets 和所有格式都被跳过。甚至没有像“RAW”或“COMMENT”这样的 JsonToken。

有没有办法使用 Jackson(或其他 Java 库)解析嵌入原始数据的 JSON?

【问题讨论】:

  • 您的 JSON 是否未被解析,或者您希望从 json 中提取 cmets?
  • 我需要操纵 JSON 保持提交不变。
  • @30thh 应该是纯Java库?还是介绍java以外的东西的房间?
  • @Nagaraj 欢迎一切有效的东西 :-)

标签: java json parsing jackson comments


【解决方案1】:

NodeJs 方式

您可以通过节点包来实现这一点 - node-comment-json

基本上,这个库是专门为保持 cmets 原样而设计的,还允许美化 JSON 的输出。

这是我在使用npm i -g comment-json 安装软件包后可以做的:

$ node
> const { parse, stringify } = require('comment-json') 
> const parsed = parse(`{"a":"b"/*------------*/,"c":"d"}`)
> prased
{ a: 'b', c: 'd' }
> parsed['a'] = 'df'
> parsed
{ a: 'df', c: 'd' }
> stringify(parsed, null, 2)
'{\n  "a": "df" /*------------*/,\n  "c": "d"\n}'

现在,我知道这是一个节点包。我们可以通过 node 使用它,或者如果确实需要通过 Java 使用它。

Java 解决方法

安装 NPM 和包:

使用frontend-maven-plugin,您可以安装node/npm 和包。所以你的 pom.xml 看起来像这样:

<plugin>
    ...
    <executions>
        <execution>
            <!-- optional: you dont really need execution ids -->
            <id>install node and npm</id>
            <goals>
                <goal>install-node-and-npm</goal>
            </goals>
            <!-- optional: default phase is "generate-resources" -->
            <phase>generate-resources</phase>

            <configuration>
                <nodeVersion>v6.9.1</nodeVersion>
            </configuration>
        </execution>
        <execution>
            <id>npm install</id>
            <goals>
               <goal>npm</goal>
            </goals>

            <!-- optional: default phase is "generate-resources" -->
            <phase>generate-resources</phase>

            <configuration>
            <!-- Install the comment-json-->
            <arguments>install -g comment-json</arguments>
            </configuration>
         </execution>
    </executions>
</plugin>

创建一个解析参数并解析所需逻辑的 NodeJs 脚本

我编写了一个示例 app.js 脚本,其中除了以下参数:

  • JSON:"{\"a\":\"b\"/*------------*/,\"c\":\"d\"}"
  • 更改密钥:"a"
  • 要更改的新值:"df"

app.js:

const {
  parse,
  stringify
} = require('comment-json');

 const parsed = parse(process.argv[2]);
 parsed[process.argv[3]] = process.argv[4];

 console.log(stringify(parsed, null, 2))

因此,如果我将其执行为:node app.js "{\"a\":\"b\"/*------------*/,\"c\":\"d\"}" "a" "df",它会在控制台上打印:

{
  "a": "df" /*------------*/,
  "c": "d"
}

使用ProcessBuilder,执行脚本并从console.log捕获输出

也使用IOUtils

List<String> commands = new LinkedList<String>();
commands.add("node");
commands.add("app.js"); // You need the actual /path/to/app.js
commands.add("{\"a\":\"b\"/*------------*/,\"c\":\"d\"}");
commands.add("a");
commands.add("df");

ProcessBuilder processBuilder = new ProcessBuilder(commands);
String output = IOUtils.toString(processBuilder.start().getInputStream(), StandardCharsets.UTF_8);

【讨论】:

  • 我不太可能实现如此复杂的集成,但感谢您的出色调查。
【解决方案2】:

不知道为什么需要从 json 解析推荐。如果您想从 json 中查看推荐,为什么不直接将 json 作为字符串读取并解析出推荐。这是阅读推荐的正则表达式示例;

final Pattern pattern = Pattern.compile("/\\*.+\\*/", Pattern.DOTALL);
final Matcher matcher = pattern.matcher("{\"a\":\"b\"/*------------*/,\"c\":\"d\"}");
matcher.find();
System.out.println(matcher.group(0));

【讨论】:

  • 我对 cme​​ts 不感兴趣。我需要更改保留 cmets 的 JSON(如果可能,还需要格式化)。我需要在 JSON 中再注入一个字段,而文档的其余部分保持不变。差异工具应仅指向具有新字段的行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-06
  • 1970-01-01
  • 1970-01-01
  • 2016-06-13
  • 1970-01-01
  • 2016-07-07
相关资源
最近更新 更多