Talend : Suppression de champs dans un JSON

Posted on Tue, Jul 20, 2021 Talend Tuto ETL JSON JAVA API

Supposons que nous avons le JSON suivant :

{
"index": 1,
"index_start_at": 56,
"integer": 39,
"float": 15.0812,
"name": "Sheryl",
"surname": "Callahan",
"fullname": "Pauline Glass",
"email": "cheryl@knowles.bv",
"bool": true
}

Nous voulons supprimer les champs index et bool

On enregistre le json d’origine dans une string

String jsonStringBefore = "{\"index\":1,\"index_start_at\":56,\"integer\":39,\"float\":15.0812,\"name\":\"
Sheryl\",\"surname\":\"Callahan\",\"fullname\":\"Pauline Glass\",\"email\":\"cheryl@knowles.bv\",\"bool\":
true}";

On utilise la librairie org.json.

On crée un objet json :

org.json.JSONObject jsonObj = new org.json.JSONObject(jsonString);

On supprime les champs souhaités :

jsonObj.remove("index");
jsonObj.remove("bool");

On enregistre le nouveau JSON dans une nouvelle string :

String jsonStringAfter = ""+jsonObj;

Au final nous obtenons dans jsonStringAfter :

{
"index_start_at": 56,
"integer": 39,
"float": 15.0812,
"name": "Sheryl",
"surname": "Callahan",
"fullname": "Pauline Glass",
"email": "cheryl@knowles.bv"
}

Voici un export d’un petit job d’exemple créé sous Talend 7.3.1 :

delete-json-fields.zip