I’m trying to construct a nested JSON object from a query string which is returned from sql. The constructed nested JSON object will be be used by angular to render it in the UI using angular2-query-builder.
input_string = "TierLevel = ‘1’ AND CompanyType = ‘7’ AND CompanyService = ’23’ AND ( City LIKE(‘%york%’) OR City LIKE(‘%cal%’) ) AND ( StateProvince = 3171 OR StateProvince = 475 OR StateProvince = 2239 OR ( Country = 224 AND Country = 1 ) )";
output_JSON_Object = {
condition: 'and',
rules: [
{
field: 'TierLevel',
operator: 'Equals',
value: '1'
},
{
field: 'CompanyType',
operator: 'Equals',
value: '7'
},
{
field: 'CompanyService',
operator: 'Equals',
value: '23'
},
{
condition: 'or',
rules: [
{
field: 'City',
operator: 'Contains',
value: 'york'
},
{
field: 'City',
operator: 'Contains',
value: 'cal'
}
]
},
{
condition: 'or',
rules: [
{
field: 'StateProvince',
operator: 'Equals',
value: '3171'
},
{
field: 'StateProvince',
operator: 'Equals',
value: '475'
},
{
field: 'StateProvince',
operator: 'Equals',
value: '2239'
},
{
condition: 'and',
rules: [
{
field: 'Country',
operator: 'Equals',
value: '224'
},
{
field: 'Country',
operator: 'Equals',
value: '1'
}
]
}
]
}
]
}
Any help is appreciated. Thanks
3
Answers
You can try using antlr to break down your input sql string into tokens and later based on the broken tokens you can construct your required json.
If your example contains all the possible variations in operators and literals, then you could use this parse function:
The parser has no error handling and assumes the input has the expected syntax. For instance:
LIKE
argument is expected to have at least one%
, and only at the start and/or at the end of the string literal and no other wildcards, so that indeed it can be identified as a "Contains", "Begins With" or "Ends With" operation.<=
,IN
or other operatorsfield operator literal
, where the literal can have parentheses around it (as forLIKE
)(
and)
is guaranteed when not used forLIKE
.Extend as needed to support other operators, syntax, and error handling.
use AST with dfs can help you, i think.