Search code examples
ballerina

Modifying a field of a JSON object in Ballerina


I have a requirement to:

  1. read a JSON object from a file.
  2. modify a single field in the json object.
  3. write it back to the file.

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?


Solution

  • 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