Transforming a Standard Query into a JSON Clause Hierarchy

I am looking to create a query system for my application that can be utilized by external systems for configuring based on specific conditions.

My plan is to utilize a JSON Clause tree on the backend, which will be evaluated recursively.

[
  "AND",
  [
    {
      "operator": "eq",
      "field": "section1.fieldabc",
      "value": "value1"
    },
    [
      "OR",
      {
        "operator": "lt",
        "field": "section2.fieldxyz",
        "value": 5000
      },
      {
        "operator": "gt",
        "field": "section2.fieldxyz",
        "value": 1000
      }
    ]
  ]
]

This structure resembles an S-expression tree for representation purposes.

While I aim to have a JSON Clause Tree in Backend, I want to spare users from having to manually write this code.

Ideally, I would like to develop a query language similar to JQL (Jira Query Language) without the need for an overly complex parser.

Is there a standardized method for implementing this? Perhaps using a library to convert a standard query language (in JS or Java).

From the user's viewpoint, the above query should appear as:

section1.fieldabc == value1 AND (section2.fieldxyz < 5000 OR section2.fieldxyz > 10000)

Answer №1

Recently, I developed a relatively straightforward parser in TypeScript capable of handling binary operators, order of operations, constants, brackets, global variables, and simple field accesses. You can find the complete source code on my GitHub repository. Additionally, here's a snippet showcasing a JS version:

const BINARY_OPERATORS = {
    // AND/OR
    'AND': 1,
    'OR': 0,
    // Equal stuff
    '==': 2,
    '!=': 2,
    '<': 2,
    '<=': 2,
    '>': 2,
    '>=': 2,
}

// Functions for parsing constants, variables, and ordering binary operations...

// Function to parse the input expression...

// Function to format the parsed expression...

console.log('=>', formatExpression(parsed));

When converted to JSON, the output looks like this:

{
    // JSON output example
}

I opted for utilizing objects with a specified type field for consistency throughout the codebase. While my implementation may seem more complex than simpler string-based approaches, it offers flexibility for future enhancements. If you're considering implementing an SQL-like syntax, my solution could be beneficial for power users.

While my code is concise and adaptable, other libraries like jQuery QueryBuilder or react-query-builder may offer more polished features for user-friendly query building experiences. It's always worth exploring existing solutions before reinventing the wheel!

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

Code to conceal navigation bar...positioned neither at the top nor at the bottom of the scroll

As a graphic designer with some coding knowledge, I'm struggling with a particular issue... I have a traditional navigation bar that only appears when the user scrolls down a bit, which I achieved through JavaScript. However, I want this to occur onl ...

The Selenium webdriver successfully refocusing on the parent window after dealing with a pop-up child window

I am facing an issue while trying to switch from a pop-up window back to the parent window that was generated by a click event. Various methods were attempted, but none of them proved successful in resolving the problem. public static String verifyHierar ...

Error message in React-router: Cannot read property 'func' of undefined, resulting in an Uncaught TypeError

When attempting to launch my react application, I encountered an error in the browser console: Uncaught TypeError: Cannot read property 'func' of undefined at Object../node_modules/react-router/lib/InternalPropTypes.js (InternalPropTypes.js: ...

How can I pass standard HTML as a component in React?

I need help creating a Higher Order Component (HOC) that accepts a wrapper component, but allows me to pass standard HTML elements as inner content. Here is an example of what I want to achieve: type TextLike = string | {type,content} const TextLikeRender ...

Obtain an array of images from the Google Places API through a nearby search functionality

Utilizing the Google Places API within a JSP to retrieve JSON data in JavaScript has been successful, except for one aspect - the photos. Despite using the nearbySearch function, the PlacePhoto object is not populating as expected. Here is the nearbySearc ...

Double the Power of jQuery Live Search with Two Implementations on a Single Website

I recently implemented a JQuery Live Search feature that is working perfectly. Here is the JQuery script: <script type="text/javascript"> $(document).ready(function(){ $('.search-box input[type="text"]').on("keyup input", function(){ ...

Establishing Node.js environment variables when invoking `npm run` command

package.json { "scripts": { "start": "NODE_ENV=development node ./index.js" } } If we wanted to pass and override NODE_ENV when running npm run start, is it possible? npm run start NODE_ENV=production ...

Why does my JavaScript code fail to retrieve input values?

When the button labeled click here is clicked, it will trigger an alert with empty values. I am curious why the alert does not display the values 400 and 400. This code snippet is from test1.php: <script src="https://ajax.googleapis.com/ajax/libs/jqu ...

Obtaining and transferring identifiers for jQuery code execution

My goal is to create a script that dynamically changes the content of a webpage using a foreach array. The HTML structure I am working with looks like this: <div id="bigleftproject"> <p>content to be replaced</p> </div> <div ...

Having trouble connecting to MongoDB using my Android application

Here are the steps I've taken: InetAddress address = InetAddress.getByName("MyPCName"); MongoClientOptions.Builder builder = MongoClientOptions.builder().connectTimeout(3000); MongoClient mongo = new MongoClient(new ServerAddress(address.getHostAddr ...

Check for support of Symbol.toStringTag in JavaScript

Can this function reliably detect the presence of @@toStringTag in all environments? function hasToStringTagSymbol() { if (Symbol && (typeof Symbol() == "symbol") && !!Symbol.toStringTag) { var xTest = function () { }; xTest.prototyp ...

How to get the most out of the $scope variable?

Is it possible to assign a regular JavaScript variable the current value of an Angular $scope variable without having their values binded together? //$scope.var1 is set to a specific value, for example, 5 var v2 = $scope.var1; //$scope.var1 is then update ...

What is the method for utilizing AngularJS to access the HTML input FileUpload FileList object?

I am looking to retrieve the values of a FileList object after selecting files using an HTML input FileUpload element. Although I can see the FileList object in the console window when I console.log it, I am facing challenges accessing the values using Ang ...

Developing a Java Jersey web service that consumes JSON requests

I have developed a web service using Java and Jersey. The objective is to receive a JSON request, parse the JSON data, and save the values onto the database. Here is an excerpt from my web service code: @Path("companies") public class Companies { @P ...

What steps should I take to create a slider using my image gallery?

I have a unique photo gallery setup that I'm struggling with: As I keep adding photos, the cards in my gallery get smaller and smaller! What I really want is to show only 4 photos at a time and hide the rest, creating a sliding effect. I attempted ad ...

The method Polygon.getTransformedVertices() is failing to return the desired array in LibGdx

I'm facing a rather perplexing issue that I can't seem to wrap my head around. Within my Helper class, there is a method called drawStar(): public void drawStar(Star star) { shapeRenderer.begin(ShapeType.Line); shapeRenderer.setColor ...

Exploring the functionality of componentWillReceiveProps within functional components

Embarking on my journey with functional components after extensively working with class components. While experimenting, I encountered a challenge: how can I incorporate the functionality of componentWillReceiveProps within the context of the useEffect h ...

org.openqa.selenium.NoSuchElementException: Element not found: Search bar

Recently, I've been attempting to utilize the search feature on LinkedIn's learning platform () First, log in to your LinkedIn account Next, click on the "Learning" link located in the top right corner of the page I navigate to the search field ...

Tips for incorporating unique styles to a component in ReactJS

Struggling to apply unique styles to a React Next.js component? Below is the code snippet for a button component: import styles from "./button.module.css"; const Button = props =>{ return( <div> <button className={styles.button}>{ ...

Transmitting a PHP Bidimensional Array to JavaScript with Ajax

I am looking to send this PHP array to JavaScript using AJAX Here is the array contained in my main.php file: $entries = ldap_get_entries($ldap, $sr); for ($i=0; $i<$entries["count"]; $i++) { if (isset($entries[$i]["cn"][0])) { $ ...