Creating a hierarchical JSON structure using a database query in JavaScript

Currently, I am in the process of building a nested JSON object by parsing a query string obtained from an SQL database. This constructed JSON object will then be utilized by Angular to display data in the user interface using angular2-query-builder.

The input query string is as follows: 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'
                        }
                    ]
                }
            ]
        }
    ]
}

Your assistance on this matter would be greatly appreciated. Thank you!

Answer №1

If your example includes a wide range of operators and literals, you can utilize the following parsing function:

function parseExpression(expr) {
    const tokens = expr.matchAll(/(\S\w*)(?:\s*(=|LIKE)\(?\s*('(?:[^']|'')*'|[-\d.]+)\)?)?/g);

    function getRule() {
        const {value: [all, field, operator, literal]} = tokens.next();
        return all == "(" 
            ? getExpression()
            : {
                field,
                operator: operator == "=" ? "Equals"
                        : literal[1] != "%" ? "Ends With"
                        : literal.at(-2) != "%" ? "Begins With"
                        : "Contains",
                value: literal[0] != "'" ? +literal
                     : (operator == "LIKE" ? literal.replaceAll("%", "") : literal)
                       .slice(1, -1).replaceAll("''", "'")
            };
    }

    function getExpression() {
        const obj = { operator: null, rules: [getRule()] };
        for (let {done, value} = tokens.next(); !done && value[0] != ")"; {done, value} = tokens.next()) {
            obj.operator = value[0].toLowerCase();
            obj.rules.push(getRule());
        }
        return obj;
    }

    return getExpression();
}

// Sample execution
const input = "TierLevel = '1' AND CompanyType = '7' AND CompanyService = '23' AND ( City LIKE('york%') OR City LIKE('%cal') OR City LIKE('%any%') ) AND ( StateProvince = 3171 OR StateProvince = 475 OR StateProvince = 2239 OR ( Country = 224 AND Country = 1 ) )";

const output = parseExpression(input);
console.log(output);

The parser lacks error handling and expects the input to adhere to the specified syntax. For instance:

  • The LIKE operation should contain at least one %, positioned only at the beginning and/or end of the string literal without any other wildcards, enabling identification as a "Contains," "Begins With," or "Ends With" operation.
  • No support is provided for <=, IN, or other operators.
  • Conditions are consistently in the format of field operator literal, with optional parentheses around the literal (such as for LIKE).
  • Spaces surrounding ( and ) are guaranteed unless used for LIKE.
  • Sequentially occurring operators are always identical (either AND or OR), with parentheses utilized to group subexpressions utilizing a different operator.
  • ...and so forth

Enhance the functionality to accommodate additional operators, syntax variations, and error management protocols as necessary.

Answer №2

One approach is to utilize antlr for parsing your input SQL string into tokens. From there, you can analyze the broken down tokens to generate the necessary JSON output.

Answer №3

Implementing the Abstract Syntax Tree (AST) along with depth-first search (dfs) could provide you with valuable assistance, in my opinion.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Javascript to modify file permissions in Google Drive

I'm new to writing and seeking amazing solutions for all the issues I encounter. I have a website hosted on Google Drive, utilizing its SDK for Javascript. Everything functions exceptionally well, except for one problem. I need to adjust the permissi ...

Tips for moving an input bar aside to make room for another

Is it feasible to have two input bars next to each other and keep one open until the other is clicked, then the first one closes as well? I attempted using a transition with "autofocus," but the bar ends up closing when clicked on in my site. If anyone ca ...

What are the steps for integrating mongoDB with an angular2 application?

I currently have my angular2 & mongoDB setup successfully. While I've managed to read JSON files using the HTTP service, my goal is to create a fully functional application with database connectivity as well. I'm seeking advice on how to con ...

Guidelines for accessing the POST request entity with Slim framework

After sending JSON data from an Android Java application using the code below: HttpPost httpPostRequest = new HttpPost(URLs.AddRecipe); StringEntity se = new StringEntity(jsonObject.toString()); httpPostRequest.setEntity(se); I am now looking to receive ...

What are the implications of AngularJS's filter on performance?

I came across an interesting article on optimizing ng-repeat in AngularJS that discussed the following: An AngularJS filter in your HTML will run multiple times during every digest cycle, even if there have been no changes in the data or conditions. Thi ...

Tips for updating the filename in a file input using AngularJS

Is it possible to dynamically change the name of a chosen file? For instance, if I select a file with the name "img1", can it be automatically changed to a different dynamic name upon selection? <input type="file" fd-input/> https://i.sstatic.net/d ...

Is it better to use an array of dictionaries or a dictionary with arrays?

My PHP page generated this JSON data. Is it an array of dictionaries or just a dictionary with keys and dictionaries inside those keys? I lean towards the latter, but the conflicting opinions are making me uncertain. Also, will the structure change when ...

What is the best method for extracting a specific value from this JSON data?

Trying to extract the text value from a JSON response? Wondering how to retrieve the 'text' field, specifically looking for "Киргизия, Бишкек, Чуйский проспект, 213" ?? { "response":{ "GeoObjectCollection" ...

Discovering the key to selecting a row by double-clicking in Vuetify's v-data-table

I'm having trouble retrieving the row by event in my v-data-table. It only gives me the event and remains undefeated. How can I catch items in the v-data-table? <v-data-table :headers="showHeaders" :page="page&quo ...

Discover an Easy Way to Scroll to the Bottom of Modal Content with Bootstrap 5 on Your Razor Page

Currently, I am developing a web application that utilizes Razor Pages and Bootstrap 5 modals to showcase dynamic content. The challenge I am facing is ensuring that the content inside the modal automatically scrolls to the bottom when the modal opens or w ...

Using $.ajax in Zend to add an additional field to a Json object

Recently, I have been experimenting with using Ajax in conjunction with the Zend framework. After following a helpful tutorial, I was able to successfully implement it. The code snippet I used to fetch the data is as follows: $('#button').click( ...

Is it possible for me to create a hyperlink that directs to a javascript function?

Here is the code I am currently using: <input class="button" type="button" value="Mark" onClick="doCheck('mark');" \> However, I would like to replace the button with a hyperlink using the <a> tag. Is it possible to achieve ...

When clicking on HTML input fields, they do not receive focus

I am facing a puzzling issue where I am unable to access the input fields and textareas on my HTML form. The JS, HTML, and CSS files are too large for me to share here. Could someone provide guidance on what steps to take when troubleshooting this unusual ...

How can you verify user identity in Firebase when making a call to a cloud function on a

I have integrated Firebase into my React Native app, and I have only enabled anonymous login feature. Currently, I am attempting to invoke a Cloud Function from the app without utilizing the firebase SDK. Instead, I intend to make the call using axios. De ...

Converting group by values into JSON in Django is a common task that can be achieved by

Currently, I am facing an issue while trying to convert my grouped data into JsonResponse in Django. The error message that keeps popping up is: AttributeError: 'dict' object has no attribute 'f_type' This function below is responsi ...

Obtaining the login status of users on my website and displaying the number of users along with their names from the database using PHP

Can anyone assist me with figuring out how to retrieve the login status of users on my website and display the count of users along with their names from the database using PHP or jQuery? Alternatively, I am also interested in simply finding out the num ...

Freemarker substitute & and &ampersand;

I am facing an issue with Freemarker. I need to eliminate all the special characters from this sentence as well as from similar sentences in the future: BLA BLA RANDOM &, RANDOM BLA In particular, I want to remove the & character. The platform ...

"Exploring the world of interactive external links within a Facebook canvas app

Within my Facebook canvas application, I have links that need to open in a new tab or page when clicked by users. How can I achieve this? To redirect users to the Facebook login page, I am currently using JavaScript location. A few months ago, I came acr ...

Detecting incorrect serialized data entries based on data types

In the scenario where the type MyRequest specifies the requirement of the ID attribute, the function process is still capable of defining a variable of type MyRequest even in the absence of the ID attribute: export type MyRequest = { ID: string, ...

Error: The javascript function is unable to execute because undefined is not recognized as a function

I've been struggling with an error in my "bubble sort" function that I wrote to organize a list of images. Whenever I run the function, I keep getting the message "Uncaught TypeError: undefined is not a function". Can anyone provide some guidance? $j ...