I have a requirement to:
My code looks like this:
json packageJson = check io:fileReadJson(packageJsonPath);
packageJson.'version = newVersion;
When I try to assign a new value to the version
field, I get the following error:
invalid operation: type 'json' does not support field access for assignment
I thought of converting the json to a user-defined type, but this action needs to be performed on multiple json files and the structure of the json is not quite fixed (even though all files will contain the version
field).
Is there a way to work around this? Or is there a different way to approach this problem?
json
is the union () | boolean | int | float | decimal | string | json[] | map<json>
. So a json
value may be a non-JSON object value too. Before attempting to use the value as a JSON object, the type needs to be narrowed down to map<json>
which represents JSON objects. Moreover, as with any map update, member access needs to be used to update the map.
map<json> packageJsonObj = check packageJson.ensureType();
packageJsonObj["version"] = newVersion;
or
if packageJson is map<json> {
packageJson["version"] = newVersion;
} else {
// handle the non-JSON object scenario
}
You can find more details in