'how to convert a CSV into JSON using Python Or Java. The csv is representation of a nested JSON (Containing array of json objects and nested objects)
I get a csv file like :
attrib1_x , attrib1_y , attrib1_z_0_p , attrib1_z_0_c , attrib1_z_1_p , attrib1_z_1_c , attrib2_R , attrib2_K , attrib3
1 , 2 , 100 , 200 , 500 , 600 , 222 , 320 ,hello
The csv represents a json like below.
{
"attrib1":{
"x":1,
"y":2,
"z":[{"p":100,"c":200},{"p":500,"c":600}]
},
"attrib2":{"R":222,"K":320},
"attrib3":"hello"
}
So basically here I get the above CSV, and need to convert it to the JSON structure shown
. Not sure how to do it. is there any library(Python/Java) which can help me with this.
If any solution/suggestion with different csv header available that will also work. i can ask the team to provide me the csv with different header names to represent the nested / arrays.
Solution 1:[1]
First you iterate the key
Then similarly iterate value
and save into csv
String eol = System.getProperty("line.separator");
try(Writer writer = new FileWriter("C:\\Users\\m.hussain\\Desktop\\CSV\\testing.csv"))
{
for (Map<String, Object> map : objectRecords)
{
for (Map.Entry<String, Object> entry : map.entrySet())
{
writer.append(entry.getKey())
.append(',');
}
break;
}
writer.append(eol);
for (Map<String, Object> map : objectRecords)
{
for (Map.Entry<String, Object> entry : map.entrySet())
{
JSONObject jsonObject;
try
{
jsonObject = new JSONObject(String.valueOf(entry.getValue()));
writer.append(jsonObject.getString("value"));
}
catch (Exception e)
{
writer.append(String.valueOf(entry.getValue()));
}
writer.append(',');
}
writer.append(eol);
}
Solution 2:[2]
JSONObject jsonObject = new JSONObject("{
"attrib1":{
"x":1,
"y":2,
"z":[{"p":100,"c":200},{"p":500,"c":600}]
},
"attrib2":{"R":222,"K":320},
"attrib3":"hello"
}");
Just try and out. It may help
Solution 3:[3]
The first row of your CSV contains field names (which uses the underline to show the hierarchical relationship) and detail data starts from the second line, and you need to transform the CSV to JSON format. Here the difficulty is dynamic parsing. It will involve grouping, recursion, loop, conditional judgment and string concatenation. The code will be rather lengthy if you try to do this in Java.
Try using SPL, the open-source Java package, to do this. It is easy and five lines of code are enough: enter image description here
SPL offers JDBC driver to be invoked by Java. Just store the above SPL script as recurse.splx and invoke it in a Java application as you call a stored procedure:
…
Class.forName("com.esproc.jdbc.InternalDriver");
con= DriverManager.getConnection("jdbc:esproc:local://");
st = con.prepareCall("call recurse()");
st.execute();
…
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | SYED MUSTAFA HUSSAIN |
Solution 2 | Frightera |
Solution 3 | LeoTaylor |