Updating Operon/JSON-values

One really important pattern to learn with Operon is to update the values. Operon has the Update -pattern for this purpose, but it is also possible to use object/array:update or core:update -functions or event the Map -pattern.

Setting up the test data

We'll start by setting up simple test-data, which we will update in the examples.

Defining the goal

Ok, now we have the simple example-data. Next we want to decide what to update from this structure.

  1. Update the first-person's lname to "baz"
  2. Update all the lname -field values to "baz", exluding the parent-objects
  3. Update all the "fname" fields to "first_name", including from the parent-objects
  4. Remove all the "parent" -objects
Now we have three simple goals and we can start.

Update value with Update-pattern

The Update-pattern is the proper way to do updates in Operon. Coupled with the Deepscan or Where -patterns we get a really powerful combination as we can see from the examples below.

Update the first-person's lname to "baz"

NOTE: Update may be abreviated with "<<", and the Path with "~". The query may be written in shorter form:

: << ~(.persons[1].lname): "baz";

Update all the lname -field values to "baz", exluding the parent-objects

For this example we use the Where-pattern. It works together with the Path-matcher (~=). The Path-matcher returns true/false, depending whether the path given to it matches the pattern it has been given. The current-value is given to Where, which goes through the structure, passing the Paths for Path-matcher. Where returns an array of all matching paths, which are then used by Update-pattern to run the updating expression.

Update all the "fname" fields to "first_name"

Here's the same, but done little bit differently:

Remove all the "parent" -objects

Update value with Map-pattern

Map-pattern iterates through the structure's first level and we can do updates while it does. Let's see how.

Update the first-person's lname to "baz"

As we can see, using Map-pattern for this update results in ridicuosly long statements, which is not Operonic.

Bonus script

Here's a script that we can use to generate test-data and test updates to learn more Operonic-patterns.