I have a sample CSV message:
header1,header2,header3
value1,value2,{"name":"John","age":30,"car":null}
How to convert it in form of embedded JSON
as in:
{
"header1": "value1",
"header2": "value2",
"header3": "{\"name\":\"John\",\"age\":30,\"car\":null}"
}
I am using Jackson
schema builder with default column separator:
CsvSchema.builder().disableQuoteChar().setUseHeader(true).build();
CsvMapper.builder().enable(CsvParser.Feature.IGNORE_TRAILING_UNMAPPABLE, CsvParser.Feature.WRAP_AS_ARRAY).build();
CodePudding user response:
You can use a csv JS library such as json-2-csv
# Global so it can be called from anywhere
npm install -g json2csv
# or as a dependency of a project
npm install json2csv --save
CodePudding user response:
You can org.json.CDL
as follows:
BufferedReader br = new BufferedReader(new FileReader("file.csv"));
String csvAsString = br.lines().collect(Collectors.joining("\n"));
String json = CDL.toJSONArray(csvAsString).toString();
try {
Files.write(Path.of("src/main/resources/output.json"), json.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
e.printStackTrace();
}