Reputation: 11
I have mentioned the code in which i have that query.I am requesting you to help me on the same lua or krakend config or Both. (Note Key is not exists)
LuaScript
local docDetails = responseData:get("DocDetails")
-- docDetails:set("D_OffersAddOn", {}) -- Init OffersAddOn is an empty array.
local discount = {
["D_Name"] = "Discount",
["D_Price"] = 0,
["D_Type"] = "value",
}
local D_OffersAddOn = docDetails:get("D_OffersAddOn")
-- D_OffersAddOn:set(0,discount)
We are getting
{
"0": {
"D_Name" : "Discount",
"D_Price" : 0,
"D_Type" : "value"
}
}
insted of this I am exepecting
[
{
"D_Name" : "Discount",
"D_Price" : 0,
"D_Type" : "value"
}
]
Line 1 --> getting DocDetails from response
Line 2 --> D_OffersAddOn key not exists in DocDetails. So I am creating an empty table
Line 3 --> I am creating the discount object(table)
Line 4 --> Selecting D_OffersAddOn array initially i created
Line 5 --> Now I am adding the discount object into an table as an array.
When I am doing below operation I am getting excepected as string but received as number.
-- D_OffersAddOn:set(0,discount)
If I am doing
docDetails:set("D_OffersAddOn", {discount})
then API returns below format.
{
"0": {
"D_Name" : "Discount",
"D_Price" : 0,
"D_Type": "value"
}
}
But I am expecting the below format
{
"DocDetails": {
"D_OffersAddOn": [
{
"D_Name" : "Discount",
"D_Price" : 0,
"D_Type" : "value"
}
]
}
}
Upvotes: 1
Views: 220
Reputation: 1
I've spent several days to figure it out. It's a shame that there is so little documentation from KrakenD in this matter. Here is a working example that creates a new JsonArray and inserts a single element to an existing array
function post_proxy()
print("postProxy fired!")
local resp = response.load();
local data = {}
local responseData = resp:data()
--Adding new JsonArray
local array = luaList:new()
array:set(0,{})
array:set(1,{})
array:get(0):set("name","xxx")
array:get(1):set("name","yyy")
responseData:set("newArray",array);
--Adding element to existing JsonArray
local col = responseData:get("collection");
local size = col:len();
local newArray = luaList:new()
local j=0
for i=0,size-1 do
j=j+1;
local element = col:get(i)
newArray:set(i,element)
end
newArray:set(j,{})
newArray:get(j):set("name","YYY")
responseData:set("collection", newArray)
end
Upvotes: 0