ARTICLEViews: 12Share  Posted by - Anonymous

Transform JSON in a key value pair to be stored per interest for all of the users

{

{

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

   }

  }

}


Auto Suggestions & Related Videos -


Rest Assured is very popular in API Test Automation. REST Assured API can be used to invoke REST web services and match ...

Store multiple key value pairs in a cookie

Python Tutorial for Beginners 5: Dictionaries - Working with Key-Value Pairs

SpringBoot : Spring Data JPA - One To Many & Join Query | Example | Java Techie

Querying Semi-Structured JSON in Snowflake

Views -