views:

37

answers:

1

I'm trying to build a handy dsl-ish query ability into my javascript.

given:

var query = "lastName = 'smith' and firstName = 'jack' or city = 'vancouver'";

what's the most elegant way of parsing this sql-esque string into usable objects such as:

[
{
 field:'lastName',
 operator:'=',
 value:'smith',
 join:'and'
},
{
 field:'firstName',
 operator:'=',
 value:'jack',
 join:'or'
},
{
 field:'city',
 operator:'=',
 value:'vancouver'
}
]

Before I start hopelessly looping I figured there would be some regex master that had a one-liner.

A: 

Create a grammar (EBNF or BNF) and then write a parser for it. Not only will you have more hair left on your head (you're going to end up pulling your hair out if you try to do this with regular expressions!), you will learn something new and cool :).

If you write a recursive-descent parser, you can easily represent your query as a tree.

Here's an EBNF to get you started:

query            ::= criterion { criterion }
criterion        ::= boolean-operator { filter }
boolean-operator ::= "not" | "or" | "and"
filter           ::= variable, "=", value
Vivin Paliath