用逗号格式化json文件? [英] format json file with comma?

查看:85
本文介绍了用逗号格式化json文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json文件.

I have a json file.

{"bla":"bla"}
{"bla":"bla"}
{"bla":"bla"}
{"bla":"bla"}
......

如何将它们格式化为有效的json类型,例如:

How can I format these into a valid json type, like:

[    
    {"bla":"bla"},
    {"bla":"bla"},
    {"bla":"bla"},
    {"bla":"bla"},
    ......
    {"bla":"bla"}
]

在每个{}之后插入逗号,最后一个除外.

Insert comma after each {} except last one.

如何在Java中做到这一点?

How can I do that in java?

谢谢.

PS:好的.这是我根据TCP响应创建的一个名为"1.json"的json文件.我将一些名称发送到服务器,并且收到响应并将其另存为文件.因为所有数据都像{"bal":"bla"} {"bal":"bla"} {"bal":"bla"} {"bal":"bla"} ...... 这是jQuery getJSON()无法读取的无效json结构.所以我想将其解析为有效类型.

PS: OK. This is a json file called "1.json" which I created from TCP response. I send some names to the server and I receive response and save as a file. Because all the data is like {"bal":"bla"}{"bal":"bla"}{"bal":"bla"}{"bal":"bla"}...... This is an invalid json structure that jQuery getJSON() couldn't read it. So I want to parse it to a valid type.

推荐答案

如果您只需要重新格式化该输入(每行JSON对象,每行一行),那么您实际上就不需要将它们转换为Java JSON对象,您可以直接读取文件并将其即时转换为新的JSON字符串:

If you are just needing to reformat that input (lines of JSON objects, one line each), then you dont really need to convert them into Java JSON objects, you can just read the file in and convert it on the fly to the new JSON string:

StringBuilder str = new StringBuilder();
BufferedReader reader = null;
    try {
    str.append("[\n");

    for( String line = reader.readLine(); line != null; line = reader.readLine() ){
        str.append(line).append(",\n");
    }

    str.setLength(str.length()-2);
    str.append(']');

} catch( Exception ex ){
    if(reader != null){ reader.close(); }
}

或类似的东西.请注意,仅当您的JSON对象是在单行中定义而不分散在多个行中时,这才起作用.

or something similar. Just note that this will only work if your JSON objects are defined on single lines not spread across multiples.

希望这会有所帮助.

这篇关于用逗号格式化json文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆