nikom
nikom

Reputation: 71

How to convert TSV data to JSON Object in java

TSV Data : enter image description here

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

I got the similar question for JQ, but how can I achieve this in java? Convert TSV file to multiple JSON arrays with jq

Upvotes: -1

Views: 355

Answers (1)

siusiulala
siusiulala

Reputation: 1060

Load file by BufferedReader and use JsonArray to format your Json output

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

Upvotes: 1

Related Questions