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

Attempt to generate a function in JavaScript that mirrors an existing one

How can I create a javascript function similar to loadAllOriginal, but with the value of the variable allEmployees being a list of employee objects (ID, FirstName, LastName)? I am attempting to implement this method in combination with autocomplete from ...

What is preventing me from refreshing my customized list view using the API?

Seeking assistance to customize a ListView using API data. Currently, the data is displayed as two TextView items instead of Title and Subtitle with an icon in the desired layout format. Looking for guidance on how to show the Line name as a row heading ...

Short-circuiting async flows on non-error events in Node.js

Node implements the CPS convention for callbacks. Typically, when a function encounters an error, it is common practice to either handle the error or callback the error to the parent function by utilizing something like return cb(err). One challenge I fac ...

The functionality of onClick and console.log seems to be malfunctioning on Nextjs

I'm currently learning NEXT but I've encountered some issues with certain functions "use client" import { useState } from 'react' export default function idk() { const [counter,setCounter]=useState(0) const add=()=> ...

A guide on incorporating a customized Google map into your website

Recently, I utilized the Google Map editing service from this site: https://developers.google.com/maps/documentation/javascript/styling This link provided me with two things: 1. A JSON code 2. The Google API link However, I am unsure about how to incorpo ...

What is the best way to display a <div> depending on the screen size in React JS using a global variable, without utilizing state management?

I am attempting to display a message based on the screen resolution in ReactJS. I am utilizing a function component and trying to accomplish this without using state, by using a global variable. const isDesktop = window.innerWidth; {isDesktop > 768 ? ...

Exploring the concept of nested JSON objects within React components

Hey there, I'm new around here. I created a Data object in ASP .Net Core which can be accessed through the GET method GetData: using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; namespace ReactImport.Controllers { [Route("api/[controller]")] ...

Trigger the activation of an input field upon clicking an image labeled "edit"

I am currently developing a website where administrators have access to a dashboard page that displays a list of users. I am looking to implement a feature that allows admins to change the roles of other users directly from the same table row. Below is th ...

What is the best way to conceal the button?

I'm working on a program that involves flipping cards and creating new ones using three components: App, CardEditor, and CardViewer. Within the CardEditor component, I am trying to implement a function that hides the button leading to CardViewer until ...

What could be causing the fluctuation in the length property of my array-like object?

Currently, I am following a JavaScript tutorial that covers the call and apply methods. One thing that has me puzzled is the behavior of an 'array-like object' used in one of the examples: var arrayLikeObj = { 0: 'Marty', 1: 78 ...

Ensuring child input components are validated upon submission using Vee-Validate and Vue.js 2

Currently, I am working on creating a Registration form with multiple "Input Field" components that require validation once the Submit button is pressed. While each input field validates individually when the text is changed, I am struggling to implement a ...

What are the steps to implement an Express Error handling middleware in my specific scenario?

I have implemented a router middleware to validate requests and a global Error handler middleware in the server.js file to handle all errors. However, I am encountering an issue within the router while trying to implement this logic. The problem is highli ...

Registration and Mapping Interface API

Recently, I have been researching information for an application that we are planning to develop for our chain of stores (approximately 20). Our goal is to reward customers with points when they check-in at our store locations. Additionally, we aim to show ...

Guide on how to combine the strings retrieved from an API

I'm having trouble concatenating multiple sentences together and highlighting specific words in each sentence. Although I can successfully highlight one sentence using the code below, I haven't been able to concatenate more than one sentence: th ...

Utilizing Angular's ng-repeat directive to dynamically generate images, with the added functionality of attempting to

I am utilizing angular-drupal to fetch data from my backend built on Drupal. My objective is to create an image gallery using the default endpoints provided by the services module. I make a call to node load to retrieve a specific node, then I extract the ...

Asynchronous Function Implementation of Cookies in JavaScript

Here's my query: Is it possible to store a cookie within an async function? For example, creating a cookie from this fetch and then accessing it later within the same function while the fetch continues to update the value each time the function is ex ...

Utilizing the `theme` property in makeStyles with Material-UI

I am currently working on passing down an muiTheme to a component through the use of ThemeProvider, and I also want to apply it to the children components. Furthermore, I aim to utilize the theme's properties in both components by creating a classes o ...

When attempting to send a request for the JSON body to Node.js using the await fetch method, I encountered an issue

Recently, I started working with node js and attempted to fetch JSON data using the code below: const req = await fetch( "http://localhost:3000/api/auth/signin", { method: "POST", header:{ 'Accept':&apo ...

An issue with the image filter function in JavaScript

I am currently working on a simple application that applies image filters to images. Below is the code I have written for this purpose. class ImageUtil { static getCanvas(width, height) { var canvas = document.querySelector("canvas"); canvas.widt ...

Convert the output of SQLAlchemy into a JSON format that includes the names of the columns

I have made the decision to transition my Django project from using Django ORM to SqlAlchemy. I am currently working on serializing the SqlAlchemy output to JSON, which includes column names. In my previous Django code, I had: logs = Log.objects.values(& ...