I'm using the Ballerina language to create a RESTful web service for order management in an online retail store as instructed in here. In the resource function which handles HTTP PUT requests, there is a piece of code which will retrieve the relevant order from a json map object(currently using to store orders, hasn't connected a database yet.) and update some of its fields with the ones from the json object that was received with the HTTP PUT request.
I've declared the json map object, ordersMap.
map<json> ordersMap = {};
The resource function that handles PUT requests have a chunk of code that goes like this:
// Get the json obejct from the payload
var updatedOrder = <@untained> req.getJsonPayload();
// Get the existing order that is required by the request from the json map object.
json existingOrder = ordersMap[orderId];
// Updating the necessaries and saving it in the map object.
existingOrder.Order.Name = updatedOrder.Order.Name;
existingOrder.Order.Description = updatedOrder.Order.Description;
ordersMap[orderId] = existingOrder;
When I try to compile the program, the compiler throws following error.
invalid operation: type 'json' does not support field access for assignment
I've looked for solutions online and couldn't find anything. I'm using Ballerina 1.2.4
This is because when you use
json
datatype the compiler cannot guarantee the fields you are accessing exists and (in case it does not exists it can't calculate the types to insert relevant entries).When you want to operate on a piece of json data, and you know the shape of this json structure it's a good idea to create relevant types and operating on those and if you want a json back, then you can convert it back to json. Unfortunately there is no straightforward way to convert to (and back) from json in Ballerina 1.2.x, if you can switch to Ballerina Swanlake track you can use something like following.
In ballerina 1.2.x
One big issue with the second approach is if the structure of incoming json value was different from what we expected, it will result in a panic due to typecast error.