{
{
"id" : 1,
"Name" : "Jane Doe",
"Age" : 30,
"Address" : "NYC, USA",
"ZIP" : "10001",
"Interest" : "Sports, Movies, Reading Books"
},
{
"id" : 2,
"Name" : "John Doe",
"Age" : 32,
"Address" : "NYC, USA",
"ZIP" : "10001",
"Interest" : "Racing, Reading Books, Trekking"
}
}
Expected Output
1. Transform the above JSON in a key-value pair to be stored per interest for all of the users. The final data structure should look like below and be stored in a CSV file.
ID NAME AGE ADDRESS ZIP INTEREST
1 Jane Doe 30 NYC, USA 10001 Sports
1 Jane Doe 30 NYC, USA 10001 Movies
1 Jane Doe 30 NYC, USA 10001 Reading Books
2 John Doe 32 NYC, USA 10001 Racing
2 John Doe 32 NYC, USA 10001 Reading Books
2 John Doe 32 NYC, USA 10001 Trekking
Solution:
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.json.*;
public class ConvertJsonToCSV {
public static void main(String[] args) throws JSONException {
String jsonArrayString = "\"{
{
\"id\" : 1,
\"Name\" : \"Jane Doe\",
\"Age\" : 30,
\"Address\" : \"NYC, USA\",
\"ZIP\" : \"10001\",
\"Interest\" : \"Sports, Movies, Reading Books\"
},
{
\"id\" : 2,
\"Name\" : \"John Doe\",
\"Age\" : 32,
\"Address\" : \"NYC, USA\",
\"ZIP\" : \"10001\",
\"Interest\" : \"Racing, Reading Books, Trekking\"
}
}\"";
JSONObject output;
try {
output = new JSONObject(jsonArrayString);
JSONArray docs = output.getJSONArray("fileName");
File file = new File("newCsvFile.csv");
String csv = CDL.toString(docs);
FileUtils.writeStringToFile(file, csv);
System.out.println("Data has been Sucessfully Writeen to "+ file);
System.out.println(csv);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
Fetch All Types of Data from JSON File in React JS | React JSON Tutorial
SpringBoot : Spring Data JPA - One To Many & Join Query | Example | Java Techie
CSD 2550 – Week 7 | Lecture 9: Arrays, Objects and JSON - David Gamez
M Query Basics for Power Query