myPatterns/JS overview

matching in JSON

For example, using the JSON matching notation, you can write the following boolean expression:
(s = match(x, "{name:{firstname:%f,lastname:%l},children:[{gender:'male',born:%b}|%_]}")) 
&& new Date().getFullYear() - s.b == 18
to match a person x whose first child is a boy 18 years old; this will match objects such as the following:
{name: {firstname: "John", lastname: "Smith"}, 
 children:[{firstname: "Eric", gender: "male", born: 1992}, 
           {firstname: "Deborah", gender: "female", born: 1996}]}
In the above, the match() statement both checks whether the object has a certain form (e.g. that the children field is an array containing a first element of a given form), and returns a "substitution" object s having the following value: {f: "John", l: "Smith", b: 1991}.

Note that this form of matching is already much more powerful than JavaScript's decomposing assignments, which cannot be used as tests and cannot check fields against constant values.

defining custom notations

Furthermore, using your own notations, you could write the same test more concisely, and with your own personal touch.

uses with AJAX

Pattern matching in JSON can simplify AJAX programming by allowing to write pattern-based queries. For instance, if we had an array of persons like the one above (possibly coming from a server database), you could extract some data from it using a simple call like:
selectMatching(persons, "{name:{firstname:%f,lastname:%l},children:[{gender:'male',born:%b}|%_]}");
which could return an array like:
[{f: "John", l:"Smith", b:1991}, 
 {f: "Matt", l:"Johnson", b:1978}]

You can try JSON queries and their use in web pages online.

Last updated on: 1/4/2010 Contact us