I have a nested JSON object like this:
{
"field1": "value1",
"field2": "value2",
"field3": {
"data": [
{
"subField1": "subValue1",
"subField2": "subValue2",
"subField3": {
"nestedField1": "nestedValue1",
"nestedField2": "nestedValue2"
},
"subField4": {
"nestedField1": {
"subNestedField1": "subNestedValue1",
"subNestedField2": "subNestedValue2"
},
"nestedField2": {
"subNestedField1": "subNestedValue1",
"subNestedField2": "subNestedValue2"
}
}
}
]
}
}
I want to set a default values if the key is not present in the JSON i receive as response. Lets say null is the default value. I want the above JSON to be transformed as below
Input (Response Json):
{
"field1": "value1",
"field2": "value2",
"field3": {
"data": [
{
"subField1": "subValue1",
"subField3": {
"nestedField1": "nestedValue1"
},
"subField4": {
"nestedField1": {
"subNestedField1": "subNestedValue1"
}
}
}
]
}
}
Output (I want it to be transformed to):
{
"field1": "value1",
"field2": "value2",
"field3": {
"data": [
{
"subField1": "subValue1",
"subField2": null,
"subField3": {
"nestedField1": "nestedValue1",
"nestedField2": null
},
"subField4": {
"nestedField1": {
"subNestedField1": "subNestedValue1",
"subNestedField2": null
},
"nestedField2": null
}
}
]
}
}
basically based on the contract I want the fields which are not present with a default value (null in this case) point to note is for nested objects if the key is not present in the response JSON for that nested object we set the value as null, we don’t create the object with its fields to set the value to null, notice field3.data.subField4.nestedField2. If the key of the nested object is present then only we check the fields inside it and set the missing fields to null.
I tried modify-overwrite-beta, to have conditional checks to set the values but it didn’t work for me, all the values were set to null if I am using modify-overwrite-beta. modify-default-beta works but if the nested object key is not present in response JSON it is creating that object and setting the fields inside to null rather than setting the nested objects key to null. I tried the combination of both modify-overwrite-beta and modify-default-beta, but I couldn’t make it work.
my current JOLT spec is
[
{
"operation": "modify-default-beta",
"spec": {
"field1": null,
"field2": null,
"field3": {
"data": {
"*": {
"subField1": null,
"subField2": null,
"subField3": {
"nestedField1": null,
"nestedField2": null
},
"subField4": {
"nestedField1": {
"subNestedField1": null,
"subNestedField2": null
},
"nestedField2": {
"subNestedField1": null,
"subNestedField2": null
}
}
}
}
}
}
}
]
2
Answers
Hi this spec will help you resolve the query:
You did it right, but instead of using "[]" in jolt spec use "*" which is used for iterating through each object.
At last I have added a sort operation to sort all fields.
What you need is to use
~
operator, which checks for the existence and nullity of the current element , along with overwrite option of the modify transformation such as