Search code examples
jsonmongodbsplittreetalend

Talend JSON structure


I am struggling with my mongodboutput because I can't figure out how to build my JSON tree. Basically I have this in the "Languages" attribute of my row:

Languages##English##fluent##German##beginner##

I would like to have :

"languages": [
            {
                "language": "English",
                "level": "fluent"
            },
            {
                "language": "German",
                "level": "beginner"
            }
        ]

I have tried this in a tJavaRow:

String delims = "##";
String[] tokens = row3.langues.split(delims);
int i = 0;
while (i < tokens.length) {
    if(i%2==0){
        row5.langue=tokens[i];
    }
    else{
        row5.niveau=tokens[i];
    }
    i++;
}

But I only get the last entry in row5 whereas I would like to duplicate the rows

Is it possible to create my own columns in a routine or java component ?


Solution

  • For those who are interrested, I solved this issue by creating my own MongoDBOuput in a tJavaRow.

    In this way, I am more able to control the creation of my JSON schema.

    For example (in a tJavaRow):

    /*Get the MongoDB connection*/
    DB db = (DB)globalMap.get("db_tMongoDBConnection_1");
    
    /*Get the collection*/
    DBCollection coll = db.getCollection("cv");
    
    /*Create the JSON object*/
    BasicDBObject doc = new BasicDBObject();
    doc.append("id", Integer.valueOf(input_row.id));
    doc.append("personne", input_row.personne);
    doc.append("position", input_row.position);
    BasicDBList langues= new BasicDBList();
        String delim="##";
        String[] tokens = input_row.langues.split(delim);
        int i = 0;
        while (i < tokens.length) {
            if(i%2==0){
                res.add(new BasicDBObject("langue",tokens[i]).append("niveau",tokens[i+1]));
            }
            i++;
        }
    doc.append("langues", langues);
    
    /*Insert in collection*/
    coll.insert(doc);
    

    My object in MongoDB :

    {
        "_id": ObjectID("556da6a905f34ffea3e3dbbe"),
        "id": 1,
        "personne": "Paul Dupont",
        "position": "Consultant BI",
        "age": "23 ans",
        "langues": [
            {
                "langue": "Anglais",
                "niveau": "courant"
            },
            {
                "langue": "Allemand",
                "niveau": "intermediaire"
            }
        ]
    }