Pattern matching of JSON with JavaScript (Part 1-design) _javascript Tips

Source: Internet
Author: User
As for the description of the filter condition, pattern matching is a very common and useful way. In JavaScript, it's quite handy to use JSON to describe patterns, so let's do a JSON pattern matching tool.

Use case design
As a dispatcher, we only need two methods: Notify and capture. One of the simplest use cases is this:
Copy Code code as follows:

Dispatcher.capture ({
"Status": 200,
"Command": "Message"
}, function (JSON) {/* Display message */});

Dispatcher.notify ({
"Status": 200,
"Command": "Message",
"Content": {
"From": "User1",
"To": "User2",
"Text": "Hello"
}
});

Of course, only local congruent matching is not enough, we need some other operators.
Copy Code code as follows:

Dispatcher.capture ({
"value1$eq": "Hello", * * equal * *
"Value2$ne" : TRUE,/* Not equal * *
"value3$lt": 0,/* Less than/
"value4$lte:1,/* less than or equal/
" Value5 $gt ": 2,/* greater than * * *
" Value6$gte ": 3,/* greater than or equal */
" value7$in ": [1, 3, 5, 7, 9],/* in * /
"Value8$nin": [2, 4, 6, 8, ten],/* not in */
"Value9$all": [1, 2, 3, 4, 5],/* all */
"Value10$ex": TR UE,/* exists * *
"value11$re":/^a.*/,/* Regular expression */
"VALUE12$LD": function (JSON) {return true;} /* lambda */
}, Function (JSON) {});

Dispatcher.notify ({
"value1": "Hello",
"value2": false,
"Value3":-1,
"value4": 1,
"Value5": 3,
"Value6": 3,
"Value7": 5,
"Value8": 5,
"Value9": [1, 3, 5, 2, 4],
"Value10": " Hello ",
Value11": "A13579",
"value12": "Anything"
})

Write down a bunch of operators, it looks like the implementation will be very complex? It's not really that complicated. In the next article, we'll discuss how to design an operator interface, and then implement the operators.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.