How to transform a nested string into a JSON object using JavaScript

I am trying to manipulate a nested query string in JavaScript. The string looks like this:

var str = "( ( Sentence starts with any of null AND Sentence starts with any of null ) AND Sentence starts with any of null )"

I want to split the string at the 'AND' operator and convert it into a JSON object structure. The desired output should resemble this:

{  
   "group":{  
      "operator":"AND",
      "rules":[  
         {  
            "group":{  
               "operator":"AND",
               "rules":[  
                  object1‌​,
                  object2
               ]
            }
         },
         object3
      ]
   }
}

Answer №1

In a broad context, your response needs some tidying up:

let text = "this is my example text AND I enjoy programming AND how awesome is this?";

let parts = text.split(' AND '); // Creates an array: ["this is my example text", "I enjoy programming", "how awesome is this?"]

let collection = {};

for(let i = 0; i < parts.length; ++i) {
  collection['piece' + i] = parts[i];
}

console.log(collection); // { piece1: "this is my example text", piece2: "I enjoy programming", piece3: "how awesome is this?"}
console.log(JSON.stringify(collection)); // provides JSON string representation of the collection

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

What is the process for filtering out a particular version of an npm package?

Here is my current configuration: "@vue/test-utils": "^1.0.0-beta.25" Can anyone recommend a way to exclude a particular version of this package while still using the caret ^ notation? I specifically need to exclude version 1.0.0-beta.31 as it has cause ...

Need assistance with jQuery AJAX?

Hey there, I'm a new member and I've gone through the different Ajax Help topics but still can't figure out why my code isn't working. Here's what I have: $(document).ready(function(){ $.ajax({ type: "GET", ur ...

What causes Vue to drop nested component data within a v-for loop?

Witness the mysterious behavior through my fiddles: Anticipated outcome: https://jsfiddle.net/o7c9mwzf/27/ By clicking "unshift," I add an element to the beginning of my items array. After setting its data, clicking "unshift" again should maintain the el ...

There is an absence of the 'Access-Control-Allow-Origin' header on the requested resource despite its existence

Currently, I am working on developing an application using Django and Phonegap. While attempting to send an Ajax Request with the following function: <script> $.ajax({ url: "http://192.168.0.101/commerce/pro ...

Utilizing ReactJS onBlur event for email field validation

Currently, I am using a MaterialUI Textfield for email input validation upon leaving the field. To achieve this, I have implemented a function triggered when the onBlur event occurs. My intention is to display an error message using helpertext. Here' ...

What are the advantages of utilizing the HttpParams object for integrating query parameters into angular requests?

After exploring different ways to include query parameters in HTTP requests using Angular, I found two methods but struggled to determine which one would be the most suitable for my application. Option 1 involves appending the query parameters directly to ...

Looking to spice up your static HTML site? Dive into the world of Ruby on

I recently developed an app that features a static HTML webpage containing text and images, and now I'm interested in incorporating Ruby on Rails to explore its capabilities further. After creating a basic RoR application, I copied the HTML content f ...

PHP is having trouble parsing values from keys in JSON data retrieved from an external API

I'm currently working on making an external API call to retrieve JSON data and display it in my web application. Here is a snippet of the JSON data obtained from the API call: JSON returned from URL: { "results":[ { "name":"Company1", "Prov ...

What is the recommended way to emphasize an input field that contains validation errors using Trinidad (JSF)?

Trinidad currently displays error messages and highlights labels of failed inputs after client-side form validation. However, I need to directly highlight the input fields themselves. Is there a way to achieve this without resorting to a hack like attach ...

The Node.js error message "Module not found"

Currently, I am working through the node.js tutorial on Lynda.com and encountering an issue with the "Error: Cannot find module". Despite having the flight module listed in the package.json file, the error persists. Up until this point, everything has bee ...

Improving the display of events with fullcalendar using ajax requests

I have integrated the fullcalendar plugin from GitHub into my project. I am looking to implement a feature where I can retrieve more events from multiple server-side URLs through Ajax requests. Currently, the initial event retrieval is functioning proper ...

What is causing the 'Invalid Hook Call' error to appear in React?

I have recently started learning React and I am currently working on converting a functional component into a class component. However, I encountered an error message that says: Error: Invalid hook call. Hooks can only be called inside of the body of a fu ...

Retrieve the variable declared within the event

How can I access a variable set in an event? Here is the code snippet: $scope.$on('event_detail', function (event, args) { $scope.id = args; console.log($scope.id); // This prints the correct value }); console.log($scope.id); // ...

Guide to implementing client-side validation in MVC 4 without relying on the model

Currently, I am developing an ASP.NET MVC 4 project where I have decided not to utilize View Models. Instead, I am opting to work with the classes generated from the Entities for my Models. I am curious if there are alternative methods to achieve this. A ...

Cypress - Mastering negative lookaheads in Regular Expressions

While experimenting with Cypress, I encountered an issue regarding a filter test. The goal is to verify that once the filter is removed, the search results should display values that were filtered out earlier. My attempt to achieve this scenario involves ...

Unexpected error occurred when attempting to fetch the jQuery value of the radio button: "Unrecognized expression syntax error"

I am facing an issue while trying to extract the value of a radio button using $("input[@name=login]"); I keep getting an "Uncaught Syntax error, unrecognized expression" message. To view the problem, visit http://jsfiddle.net/fwnUm/. Below is the complet ...

Discovering the values within a separate JSON object

I have a collection of json objects that include information about different languages and user details. Languages User Details The user details contain a field for languages, which can have multiple values. Below is a sample json: $scope.languages = ...

Having trouble getting the jQuery function to update text properly

I'm curious to understand the behavior happening in this code snippet. It seems like updating the list item by clicking doesn't work as expected using the initial method. But when rearranging the JavaScript code, it displays the correct value wit ...

Can we determine if a user's operating system has disabled animations?

In my frontend project with React, I am incorporating an animation within a component. However, I want to cater to users who have disabled animations in their settings by replacing the animated content with a static image. Is there a method to detect if ...

Tips for adding spacing when the sidebar collapses and expands in a React application

I am attempting to achieve a layout where the body adjusts its space when the sidebar collapses and expands. Here is how it appears when the sidebar expands: see expanded sidebar here And this is how it looks when the sidebar collapses: see collapsed s ...