如何在java中将TSV数据转换为JSON对象

gr8qqesn  于 2023-01-06  发布在  Java
关注(0)|答案(1)|浏览(217)

TSV数据:

Required OutPut :
[{
candidates: {
id:"agent_4",
text = "can i get a confirmation code",
count = 2},
{
id:"agent_11",
text = "text_2",
count =3},
}]

对于JQ,我也有类似的问题,但是如何在java中实现呢?

jexiocij

jexiocij1#

通过BufferedReader加载文件,并使用JsonArray化Json输出

BufferedReader reader = new BufferedReader(new FileReader("data.tsv"));

    String[] fieldNames = reader.readLine().split("\t");

   
    List<JSONObject> rows = new ArrayList<>();

    // Read tsv file line by line
    String line;
    while ((line = reader.readLine()) != null) {
        
        String[] fields = line.split("\t");

        JSONObject row = new JSONObject();
        for (int i = 0; i < fieldNames.length; i++) {
            row.put(fieldNames[i], fields[i]);
        }
        rows.add(row);
    }

    reader.close();

    // Convert the list of rows to a JSON array
    JSONArray array = new JSONArray(rows);

相关问题