In my spring-boot project, I am fetching information from an external API in a JSON format.
The response is represented as follows:
{
"id":237,
"first_name":"LeBron",
"last_name":"James",
"position":"F",
"height_feet": 6,
"height_inches": 8,
"weight_pounds": 250,
"team":{
"id":14,
"abbreviation":"LAL",
"city":"Los Angeles",
"conference":"West",
"division":"Pacific",
"full_name":"Los Angeles Lakers",
"name":"Lakers"
}
}
My task is to return a CSV file from this JSON response.
I was looking for some info on the internet and only was able to find a conversion of a regular JSON to CSV, but the JSON response I am getting is nested and the conversion didn’t work.
How can I make it happen?
What should I do?
Any help will be appreciated.
2
Answers
One way to do this is to pre-process the JSON data and transform it into a flat JSON structure. You could write your own method to do this or you can use JOLT library to do this:
Sample spec
Will transform the JSON to
You can read more about JOLT here – https://github.com/bazaarvoice/jolt#Demo
You can also play around and test your spec live at the Demo page they have created at http://jolt-demo.appspot.com/#inception
Edit: After reading though the docs a bit more – here is a shorter version of the spec that will achieve similar result as the one given above:
You can use library Josson to do the job.
https://github.com/octomix/josson
Your example is an JSON object
Transformation
Output
If the input is an JSON array
Transformation
Output