What is the JSON to CSV Converter in under 10 Lines of Code

Question

Source: https://www.quora.com/What-is-the-JSON-to-CSV-converter-in-under-10-lines-of-code

Answer

Probably only SPL – a Java open-source package – can make it with no more than 10 lines of code.

Suppose we have a JSON file json.json:

{
"array":[
{
"id":1,
"name":"Tom"
},
{
"id":2,
"name":"Jerry"
},
{
"id":3,
"name":"Lucy"
}
]
}

And we are trying to convert it to a CSV file (json.csv):

id,name

1,Tom

2,Jerry

3,Lucy

SPL needs only one line of code to get this done:

A

1

=file("json.csv").export@ct(json(file("json.json").read()).array)

 

SPL offers JDBC driver to be invoked by Java. Just store the above SPL script as json2csv.splx and invoke it in a Java program as you call a stored procedure:

Class.forName("com.esproc.jdbc.InternalDriver");

con= DriverManager.getConnection("jdbc:esproc:local://");

st=con.prepareCall("call json2csv()");

st.execute();

Or execute the SPL string within a Java program as we execute a SQL statement:

st = con.prepareStatement("==file(\"json.csv\").export@ct(json(file(\"json.json\").read()).array)");
st.execute();

It is also convenient to handle a multilevel JSON file in SPL.

View SPL source code.