请求Jolt Transform实现动态属性转键值对格式转换
Jolt转换规则实现JSON动态属性转Key/Value键值对
输入JSON
{ "Boutique": [ { "ID": "1", "codePdv": "1000000", "codeSav": "1100000", "contrats": [ { "_type": "ContratFonds", "nomFournisseur": "LOIS" }, { "_type": "ContratEau", "nomFournisseur": "Veolia", "comprisDansLesCharges": false, "numeroCompteur": "99Z928" }, { "_type": "ContratClimatisation", "nomFournisseur": "CLIM" } ] }, { "ID": "2", "codePdv": "2000000", "codeSav": "2200000", "contrats": [ { "_type": "ContratVideosurveillance", "dateDebut": "2020-12-01", "dateFin": "2024-12-01", "nomFournisseur": "E8MA", "dateAutorisationCameras": "2020-12-30", "ligneAlarme": "+33188888489", "nbCamerasAutorisees": 3 }, { "_type": "ContratClimatisation", "nomFournisseur": "LACLIM" } ] } ] }
期望输出JSON
{ "pointsDeVente": [ { "ID": "1", "codePdv": 1000000, "codeSav": 1100000, "contrats": [ { "Contrat": [ { "Key": "_type", "Value": "ContratFonds" }, { "Key": "nomFournisseur", "Value": "LOIS" } ] }, { "Contrat": [ { "Key": "_type", "Value": "ContratEau" }, { "Key": "nomFournisseur", "Value": "Veolia" }, { "Key": "comprisDansLesCharges", "Value": false }, { "Key": "numeroCompteur", "Value": "99Z928" } ] }, { "Contrat": [ { "Key": "_type", "Value": "ContratClimatisation" }, { "Key": "nomFournisseur", "Value": "CLIM" } ] } ] }, { "ID": "2", "codePdv": 2000000, "codeSav": 2200000, "contrats": [ { "Contrat": [ { "Key": "_type", "Value": "ContratVideosurveillance" }, { "Key": "dateDebut", "Value": "2020-12-01" }, { "Key": "dateFin", "Value": "2024-12-01" }, { "Key": "nomFournisseur", "Value": "E8MA" }, { "Key": "dateAutorisationCameras", "Value": "2020-12-30" }, { "Key": "ligneAlarme", "Value": "+33188888489" }, { "Key": "nbCamerasAutorisees", "Value": 3 } ] }, { "Contrat": [ { "Key": "_type", "Value": "ContratClimatisation" }, { "Key": "nomFournisseur", "Value": "LACLIM" } ] } ] } ] }
注:输出示例中第二个对象的ID、codePdv、codeSav值疑似输入笔误,以下规则基于输入原数值转换。
Jolt转换规则
[ { "operation": "shift", "spec": { "Boutique": { "*": { "ID": "pointsDeVente[&1].ID", "codePdv": "pointsDeVente[&1].codePdv", "codeSav": "pointsDeVente[&1].codeSav", "contrats": { "*": { "*": { "$": "pointsDeVente[&3].contrats[&1].Contrat[&2].Key", "@": "pointsDeVente[&3].contrats[&1].Contrat[&2].Value" } } } } } } }, { "operation": "modify-overwrite-beta", "spec": { "pointsDeVente": { "*": { "codePdv": "=toInteger", "codeSav": "=toInteger" } } } } ]
规则说明
- Shift操作:
- 将顶层
Boutique数组重命名为pointsDeVente,保留ID、codePdv、codeSav的层级关系。 - 遍历
contrats数组里的每个合同对象,把每个对象的键值对转成Key/Value结构:$获取当前字段的键名作为Key值;@获取当前字段的属性值作为Value值;- 用
&3、&1、&2定位层级,确保每个合同的键值对正确归属到对应Contrat数组中。
- 将顶层
- Modify操作:
- 将
codePdv和codeSav的字符串类型转为整数类型,匹配期望输出格式要求。
- 将
内容的提问来源于stack exchange,提问作者Karim Gafsi
相关产品推荐
相关产品推荐

