Skip to content

Filter

Mpl has builtin support for advanced filtering of Json document. Apart from range indexes on Json array and wildcard in Json maps, a conditional can also be specified as a subscript in indexed variable. The syntax for conditional is [?..]. Conditional statement inside [?] can be any conditional statements as supported by 'if-else' conditional clause. e.g., x[*][? .name == c*]. Here we are comparing Json value name with wildcard c*. Note that an id inside conditional starts with . to indicate a relative ID inside Json document. Relative ID, means at the level on which subscript is applied the id (here .name) should be the key of the doc. Without a . the ID will be treated as regular Mpl variable, not a Json key. in below statement, name is key in animals and wildanimals part of the Json. a on the other hand is a regular Mpl variable.

a = "lion"
x = json {"animals" :{"name": "cow", "color":"white"}, "wildanimals":{"name": "lion", "color":"ochre"}}
x[*][? .name == a].color

output is:

"orchre"

The filter statement is like any other dotted id in Mpl. We can use the same notation to set values. e.g.,

x = json {"animals" :{"name": "cow", "color":"white"}, "wildanimals":{"name": "lion", "color":"ochre"}}
x[*][? .name == a].color = "yellow"
x.wildanimals.color

output is:

"yellow"

Above example has one level of projection as a result of wildcard *, but multilevel is also supported. e.g.,

x = json {"animals" : {"mammals": [{"nm":"lion"}, {"nm":"cow"}], "birds":[{"nm":"sparrow"}, {"nm":"dove"}]}}
x[*][*][].nm

output is:

"lion","cow","sparrow","dove"

Sometimes seemingly simple but complex filtering requirements comes up for json maps. to_keyval() and from_keyval() can be very handy for such cases. User with experience with jq tool would be familiar with this. In the following json we want to extract all objects with value ignore.

y = json {"#general": "ignore","#random": "ignore",  "#admins": "delete"}
y.to_keyval()[?.value == "ignore"].from_keyval()

output is:

{"#general":"ignore","#random":"ignore"}

for details on inner workings of these json methods, refer to the Json type chapter.