Convert a rowwise CSV file to a multilayer JSON string

In the following CSV file, the first 3 columns are categories and the rest two columns are detail data.

user_id,nickname,joinDate,product_id,price

1,kmh,2023-07-24,P131,3000

1,kmh,2023-07-24,P132,4000

1,kmh,2023-07-24,P133,7000

1,kmh,2023-07-24,P134,9000

2,john,2023-07-24,P135,2500

2,john,2023-07-24,P136,6000

3,alice,2023-07-25,P137,4500

3,alice,2023-07-25,P138,8000

user_id,nickname,joinDate,product_id,price

1,kmh,2023-07-24,P131,3000

1,kmh,2023-07-24,P132,4000

1,kmh,2023-07-24,P133,7000

1,kmh,2023-07-24,P134,9000

2,john,2023-07-24,P135,2500

2,john,2023-07-24,P136,6000

3,alice,2023-07-25,P137,4500

3,alice,2023-07-25,P138,8000

Use Java to implement a task: Convert the CSV file to a multilayer JSON string. Below is part of the result:

[{

"user_id": 1,

"nickname": "kmh",

"joinDate": "2023-07-24",

"orders": [{

"product_id": "P131",

"price": 3000

}, {

"product_id": "P132",

"price": 4000

}, {

"product_id": "P133",

"price": 7000

}, {

"product_id": "P134",

"price": 9000

}]

},

…]

[{

"user_id": 1,

"nickname": "kmh",

"joinDate": "2023-07-24",

"orders": [{

"product_id": "P131",

"price": 3000

}, {

"product_id": "P132",

"price": 4000

}, {

"product_id": "P133",

"price": 7000

}, {

"product_id": "P134",

"price": 9000

}]

},

…]

SPL code:

=json(T($[d:/data.csv]).group(user_id,nickname,joinDate;~.new(product_id,price):orders))

T()function reads a CSV file as a structured data object; $[] represents a string. json()function converts a multilayer structured data object to a multilayer JSON string. group() function groups data and computes each group of data; symbol ~ represents the current group. new() function creates a new structured data object.

Read How to Call a SPL Script in Java to find how to integrate SPL into a Java application

Source:https://stackoverflow.com/questions/76754157/how-to-change-an-unnormalized-csv-file-to-a-complex-json-or-java-object