多维JSON转CSV,非嵌套CSV转换在JAVA中可行。

huangapple go评论77阅读模式
英文:

Multidimentional JSON to CSV , non-nested CSV convertion working in JAVA

问题

public static void main(String[] args) throws JSONException {

    String userJsonFile = "C:\\Users\\Administrator\\Desktop\\jsonRes\\json_format_user_data_input_file.json";

    try {
        userJsonAsString = readFileAsAString(userJsonFile);
    } catch (Exception e1) {
        e1.printStackTrace();
    }
    JSONObject output;
    try {
        output = new JSONObject(userJsonAsString);
        JSONArray docs = output.getJSONArray("users");

        File file = new File("C:\\Users\\Administrator\\Desktop\\jsonRes\\EmpDetails.csv");
        String csv = "issuerType,issuerAssignedId\n"; // Adding header row

        for (int i = 0; i < docs.length(); i++) {
            JSONObject user = docs.getJSONObject(i);
            JSONArray identities = user.getJSONArray("identities");

            for (int j = 0; j < identities.length(); j++) {
                JSONObject identity = identities.getJSONObject(j);
                String signInType = identity.getString("signInType");
                String issuerAssignedId = identity.getString("issuerAssignedId");
                csv += signInType + "," + issuerAssignedId + "\n";
            }
        }

        FileUtils.writeStringToFile(file, csv);
        System.out.println("Data has been Successfully Written to " + file);
        System.out.println(csv);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private static String readFileAsAString(String inputJsonFile) throws Exception {
    return new String(Files.readAllBytes(Paths.get(inputJsonFile)));
}
英文:

I have a JSON file which I need to flat and create a CSV from it. I was able to convert to CSV (I have a "users" wrapper) but inside "users" there is another wrapper named "identifiers", I want to iterate them as well and create a field for them.

I have a JSON file which looks like this :

{
&quot;users&quot;: [
{
&quot;displayName&quot;: &quot;Sharad Dutta&quot;,
&quot;givenName&quot;: &quot;&quot;,
&quot;surname&quot;: &quot;&quot;,
&quot;extension_user_type&quot;: &quot;user&quot;,
&quot;identities&quot;: [
{
&quot;signInType&quot;: &quot;emailAddress&quot;,
&quot;issuerAssignedId&quot;: &quot;kkr007@gmail.com&quot;
}
],
&quot;extension_timezone&quot;: &quot;VET&quot;,
&quot;extension_locale&quot;: &quot;en-GB&quot;,
&quot;extension_tenant&quot;: &quot;EG12345&quot;
},
{
&quot;displayName&quot;: &quot;Wayne Rooney&quot;,
&quot;givenName&quot;: &quot;Wayne&quot;,
&quot;surname&quot;: &quot;Rooney&quot;,
&quot;extension_user_type&quot;: &quot;user&quot;,
&quot;identities&quot;: [
{
&quot;signInType&quot;: &quot;userName&quot;,
&quot;issuerAssignedId&quot;: &quot;kkr007&quot;
}
],
&quot;extension_timezone&quot;: &quot;VET&quot;,
&quot;extension_locale&quot;: &quot;en-GB&quot;,
&quot;extension_tenant&quot;: &quot;EG12345&quot;
}
]
}

I am trying to convert the JSON to CSV and this is what I was able to do :

多维JSON转CSV,非嵌套CSV转换在JAVA中可行。

Below is the code : As you can see, my JSON is wrapped inside a "users" type wrapper and in the JSON i have one more wrapper "identities", with the code that I did, I am able to iterate but the "identites" is coming out as JSON blob, I want something like this in place of identites

issuerType       issuerAssignedId
bla bla bla      bla bla bla

and not a JSON nested blol for identites.

public static void main(String[] args) throws JSONException {
String userJsonFile = &quot;C:\\Users\\Administrator\\Desktop\\jsonRes\\json_format_user_data_input_file.json&quot;;
try {
userJsonAsString = readFileAsAString(userJsonFile);
} catch (Exception e1) {
e1.printStackTrace();
}
JSONObject output;
try {
output = new JSONObject(userJsonAsString);
JSONArray docs = output.getJSONArray(&quot;users&quot;);
File file = new File(&quot;C:\\Users\\Administrator\\Desktop\\jsonRes\\EmpDetails.csv&quot;);
String csv = CDL.toString(docs);
FileUtils.writeStringToFile(file, csv);
System.out.println(&quot;Data has been Sucessfully Writeen to &quot; + file);
System.out.println(csv);
} catch (Exception e) {
e.printStackTrace();
}
}
private static String readFileAsAString(String inputJsonFile) throws Exception {
return new String(Files.readAllBytes(Paths.get(inputJsonFile)));
}

答案1

得分: 1

欢迎来到SO!正如你所说,“identities”是“users”数组中每个元素内部的嵌套JSON数组。因此,当你将其展平为更多或更少关系型格式(例如CSV)时,通常需要为“identities”数组的每个元素重复其余信息。

无论你使用哪个JSON解析库(你的代码片段中使用的JSONObject,我假设是来自org.json的jar包?),你都需要遍历JSONArray文档,并且对于每个元素调用getJSONArray("identities")。

由于它是一个嵌套数组,你需要两个循环来处理这种情况。

外部循环用于“users”数组,内部循环用于“users”数组中每个元素的“identities”。

请仅将以下代码段用作参考。已根据你的代码片段进行了编写。请使用标准的变量命名和实践。这只是为了展示逻辑:

String userJsonAsString = "";
StringBuilder sBuild = new StringBuilder();
StringBuilder sBuild2 = new StringBuilder();
try {
    userJsonAsString = readFileAsAString(userJsonFile);
} catch (Exception e1) {
    e1.printStackTrace();
}
JSONObject output;
try {
    output = new JSONObject(userJsonAsString);
    JSONArray docs = output.getJSONArray("users");
    
    Iterator<Object> iter = docs.iterator();
    
    while(iter.hasNext()) {
        JSONObject userEleObj = (JSONObject) iter.next();
        JSONArray nestedIdArray = userEleObj.getJSONArray("identities");
        Iterator<Object> nestIter = nestedIdArray.iterator();
        
        while(nestIter.hasNext()) {
            JSONObject identityEleObj = (JSONObject) nestIter.next(); 
            identityEleObj.keySet().forEach(key -> sBuild2.append(identityEleObj.get(key) + ","));
            userEleObj.keySet().forEach(key -> {
                if (StringUtils.equals(key, "identities")) {
                    sBuild.append(sBuild2.toString());
                    sBuild2.replace(0, sBuild2.length(), "");
                } else {
                    sBuild.append(userEleObj.get(key) + ",");
                }
            });
        }
        sBuild.replace(sBuild.lastIndexOf(","), sBuild.length(), "\n");
    }
   
    System.out.println(sBuild);
} catch (Exception e) {
    e.printStackTrace();
}
英文:

Welcome to SO!
As you rightly said, "identities" is a nested JSON Array inside each element of the "users" array. So, when you flatten into a more-or-less relational format (here CSV), you would typically need to repeat the rest of the info for each element of the "identitites" array.

Now, whichever JSON parsing library you are using (JSONObject in you snippet, I am assuming comes from org.json jar?), you would need to iterate through the JSONArray docs and for each element call the getJSONArray("identities").

Since it is a nested array, you would need two loops to handle this scenario.

outer loop for the "users" array and a nested loop for the "identities" on each element of the "users" array.

Please use the below snippet as a reference only. Have written according to your code snippet. Please use standard variable naming and practices. This is just to show you the logic

String userJsonAsString=&quot;&quot;;
StringBuilder sBuild = new StringBuilder();
StringBuilder sBuild2 = new StringBuilder();
try {
userJsonAsString  = readFileAsAString(userJsonFile);
} catch (Exception e1) {
e1.printStackTrace();
}
JSONObject output;
try {
output = new JSONObject(userJsonAsString);
JSONArray docs = output.getJSONArray(&quot;users&quot;);
Iterator&lt;Object&gt; iter =   docs.iterator();
while(iter.hasNext()) {
JSONObject userEleObj = (JSONObject)iter.next();
JSONArray nestedIdArray = userEleObj.getJSONArray(&quot;identities&quot;);
Iterator&lt;Object&gt; nestIter = nestedIdArray.iterator();
while(nestIter.hasNext()) {
JSONObject identityEleObj = (JSONObject)nestIter.next(); 
identityEleObj.keySet().stream().forEach(key -&gt; sBuild2.append(identityEleObj.get(key)+&quot;,&quot;));
userEleObj.keySet().stream().forEach(key -&gt; {
if(StringUtils.equals(key, &quot;identities&quot;)) {
sBuild.append(sBuild2.toString());
sBuild2.replace(0, sBuild2.length(), &quot;&quot;);
} else {
sBuild.append(userEleObj.get(key)+&quot;,&quot;); 
}
});
}
sBuild.replace(sBuild.lastIndexOf(&quot;,&quot;), sBuild.length(), &quot;\n&quot;);
}
System.out.println(sBuild);
} catch (Exception e) {
e.printStackTrace();
}

huangapple
  • 本文由 发表于 2020年9月16日 21:13:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/63920843.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定