Question

I have a pipe separated file with different delimiters such as given below,

c_prd_id||13043|L|

c_prd_cd||c13043|L|

c_title||14k Gold Two Tone Sparkle Chain Necklace|L|

c_alt_tag||14k Gold Two Tone Sparkle Chain Necklace|L|

c_desc||Add a little dazzle</strong> to your wardrobe with this two-tone gold chain.|L|

c_web_tmp||collectionBTemplate|L|

c_val_icons||Online_Exclusive.gif|L|

c_r_cnt||2|L|

c_r_val||5|L|

c_child_prd||281506|L|

c_child_prd||281527|L|

c_child_prd||281544|L|

c_prc_dsply_cd||REG|L|

c_create_dt||1340214009|L|

c_inv||0|L|

c_primary_type||Jewelry|L|

c_prd_type||Necklaces|L|

c_prd_subtype||Necklaces|L|

|R||L|

c_prd_id||13045|L|

c_prd_cd||c13045|L|

c_title||14k Gold Two-Tone Singapore Chain Necklace|L|

c_alt_tag||14k Gold Two-Tone Singapore Chain Necklace|L|

c_desc||Glamorous!Enhance your jewelry collection with this delicate 14k yellow gold and 14k white gold Singapore chain.|L|

c_web_tmp||collectionBTemplate|L|

c_val_icons||Online_Exclusive.gif|L|

c_r_cnt||1|L|

c_r_val||5|L|

c_child_prd||281507|L|

c_child_prd||281528|L|

c_child_prd||281545|L|

c_prc_dsply_cd||REG|L|

c_create_dt||1340214010|L|

c_inv||0|L|

c_primary_type||Jewelry|L|

c_prd_type||Necklaces|L|

c_prd_subtype||Necklaces|L|

|R||L|

I need to convert these delimited data into JSON format. Please Advice.

Was it helpful?

Solution

You can do it with some split and replace operations. Here is a example in Java for your content, you can convert it to json format calling toJsonArr method.

public static String toJsonArr(String src){
    StringBuilder builder = new StringBuilder();
    String objArray[] = src.split("\\|R\\|\\|L\\|");
    builder.append("[");
    for(String obj : objArray){
        builder.append(toJsonObj(obj)).append(",");
    }

    //remove last comma ,
    String str = builder.substring(0, builder.length()-1);

    return str+"]";
}

public static String toJsonObj(String src){
    StringBuilder builder = new StringBuilder();
    String elemArray[] = src.split("\\|L\\|");
    builder.append("{");
    for(String elem : elemArray){
                    //for empty lines
        if(elem.trim().length()!=0)
            builder.append(toJsonElem(elem)).append(",");
    }

    //remove last comma ,
    String str = builder.substring(0, builder.length()-1);

    return str+"}";
}

public static String toJsonElem(String src){
    StringBuilder builder = new StringBuilder();
    builder.append("\"").append(src.trim().replaceAll("\\|\\|", "\":\"")).append("\"");
    return builder.toString();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top