How can a string be transformed into a JavaScript Object without using JSON?

I have a good grasp on parsing a valid JSON string using JSON.parse('{"key" : "value"}').

But what happens when dealing with a valid JS object, but invalid JSON, such as: JSON.parse("{ key : 'value'}")? The outcome of this example is an error:

Uncaught SyntaxError: Unexpected token k in JSON at position 2

My current focus is on a more intricate task. I aim to parse a string representing a JS object containing RegEx (not supported by JSON, but accepted in JS) into a JS object :

'{ key1 : /val1/g , key2 : /val2/i }'

The ultimate goal is to utilize this object with Mongoose and search for documents using it :

Model.find({
     key1 : /val1/g ,
     key2 : /val2/i
})

I have made attempts to apply a rather complex RegEx to the String, replacing /val1/g with new RegEx("val1","i") :

str = str.replace( /\/(.+?)\/(g?i?).+?(?=,|})/g , "new RegExp(`$1`,`$2`)" )

The .replace() function successfully manipulates the string as intended. This results in:

{ key1 : new RegExp("val1","g") , key2 : new RegExp("val2","i") }

However, attempting to use JSON.parse on it still fails because new RegEx("val1","i") is not a valid value.

Answer №1

In the case that you have control over and trust the text being converted, eval can be used:

var str = '{ key1 : /val1/g , key2 : /val2/i }';
var obj = eval("(" + str + ")");
console.log(obj.key1);

It's important to note that when using eval, if your expression starts with {, it should be wrapped in () so the parser recognizes it as an object initializer, not a block.

A few things to keep in mind about using eval:

  1. It allows for executing arbitrary code. Therefore, you must fully trust the text being evaluated. Avoid evaluating user input.

  2. Code within an execution context containing a call to eval is difficult to optimize because the JavaScript engine cannot predict the string content during parsing. To potentially improve performance, consider encapsulating this logic in a separate function called from your main logic instead of embedding it directly.

Answer №2

I encountered a similar issue which I managed to resolve using the split and reduce methods.

const parseStringToObject = (stringToParse) => {
    if(typeof stringToParse === 'string'){
        let currentKey = '';
        const keyValPairArr = stringToParse.replace('{','').replace('}','').split(':');
        return keyValPairArr.reduce((obj,current,index,arr)=>{
            const previousKey = currentKey;
            const arrKeyVal = current.trim().split(',');
            currentKey = index!==arr.length-1?arrKeyVal.pop().trim():'';
            const previousVal = arrKeyVal.join(',');
            if(previousKey&&previousVal!=='')obj[previousKey]=previousVal;
            return obj;
        },{})
    }else{
        return stringToParse||{};
    }
}

// Here are some sample results

const example1 = parseStringToObject('{first : 1, second : 2nd, third: "third, 3rd" }')
console.log(example1) // output: {first: '1', second: '2nd', third: '"third, 3rd"'}

This function will return either an empty object or an object converted from the provided string.

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

Breaking down classes and cross-referencing them with a different DIV using JQuery

Trying to create a variable named relatedBoxes that will store checkboxes sharing similar classes as the box div. To do this, I am splitting up the classes and storing them in a variable called splitClass. Now, all that's left is to find out if any o ...

Error caught: The `onClick` listener was anticipated to be a function, but instead, it was found to be of type `object` in

While attempting to delete a customer entry with a specific id, I encountered an issue in my customers.js file. Despite adding a delete function, the entry was not being removed successfully. The console displayed the following error: caught Error: Expec ...

Unraveling intricate JSON structures into DataFrames using Julia

I'm in the process of translating some Python code into Julia and I'm facing a challenge with reading nested JSON data into a DataFrame. Is there an easy way to accomplish this in Julia? Here's my current Julia code: r = HTTP.get(url_instru ...

Issue: Error message - Unhandled promise rejection: NodeInjector error - ControlContainer not found

I'm having trouble validating a form and encountering an error. I tried implementing the suggestions provided in the following threads without success: Getting error suddenly in Angular Error: NodeInjector: NOT_FOUND [ControlContainer] Using forms i ...

Guide on linking an XML reply to TypeScript interfaces

Currently, I am faced with the task of mapping an XML response (utilizing text XMLHttpRequestResponseType) from a backend server to a TypeScript interface. My approach has been to utilize xml2js to convert the XML into JSON and then map that JSON to the Ty ...

Transmit object from NodeJS to PHP

I am attempting to transmit an object containing two key/value pairs and I would like to retrieve it on the receiving end when Apache connects to it. This is how my nodejs server is set up: var sWeather = {"url1": "something", "url2": "another"}; var oWe ...

Aligning Description Item components horizontally in antdLearn how to easily horizontally align Description

Currently, I am utilizing the `antd` Description components. In this scenario, when there is no `title` for the items, the value should be aligned to the left. You can see an example of this alignment in the image below: https://i.sstatic.net/Ah70f.png I ...

Vue.js Pagination Issue - Current Page Number Beyond Maximum Page Limit

I'm currently working on incorporating pagination into a table showcasing data for Magic: The Gathering cards. By default, the table displays only 5 items per page, with options to select pages and set the number of results per page at the bottom of ...

JavaScript inserted into debug console by developer

Is there a method to troubleshoot code that has been added through the firefox developer console terminal? For example, I added document.onkeydown = function(event) { // code logic for checking keys pressed } If only I could determine which .js file t ...

What are some ways I can integrate my Json object into my IONIC app rather than relying on a hardcoded object?

I stumbled upon this IONIC app's services.js file and found an example using a hardcoded object called "employees." Instead of using the hardcoded object, I wanted to use a JSON file. However, my attempt to make this change did not work as expected. I ...

Using a structural directive in Angular 2 that accepts a String as an input

I am attempting to develop a custom structural directive using the example provided here When trying to pass a string as an input with a slight modification, I encountered an issue where the input value was returning 'undefined' when calling th ...

Trigger file upload window to open upon clicking a div using jQuery

I utilize (CSS 2.1 and jQuery) to customize file inputs. Everything is working well up until now. Check out this example: File Input Demo If you are using Firefox, everything is functioning properly. However, with Chrome, there seems to be an issue se ...

What is the best way to incorporate this HTML and script into a React component?

After receiving the embedded HTML and script from a platform, I discovered that a button triggers the script. It was originally designed to be embedded on a website, but I am attempting to integrate it into a React application. Here is the code provided fo ...

Interval function failing to update information on Jade template

Currently, I am working on a Node app using Express and Jade. My aim is to retrieve JSON data from an API and have it refresh on the page periodically. To achieve this, I have created an empty div where I intend to inject the contents of a different route/ ...

Retrieve data by sorting based on the count column in a joined table with Sequelize

I've been struggling to make this work for some time and was hoping for some guidance. OBJECTIVE: I'm attempting to sort the posts by the number of likes they currently have. CURRENT: const posts = await db.post.findAll({ include: [ db.user ...

There is no result being returned by Model.findOne()

Why does Model.findOne() return null even when a valid collection is present in the respective Model? app.post("/fleetManagement", (req, res) => { const requestedDriverID = req.body.driverId; console.log(requestedDriver ...

Modifying an onClick handler function within a react element located in a node module, which points to a function in a prop declared in the main Component file

I have successfully implemented the coreui CDataTable to display a table. return ( <CDataTable items={data} fields={fields} ... /> ) Everything is working smoothly, but I wanted to add an extra button in the header of the C ...

The message "The property 'layout' is not found on the type 'FC<WrapperProps>' in Next.js" is displayed

I encountered an error in my _app.tsx file when attempting to implement multiple layouts. Although the functionality is working as expected, TypeScript is throwing an error Here is the code snippet: import Layout from '@/components/layouts&apo ...

Updating Tailwind CSS to accommodate older web browsers by converting modern rgba() notation to be browser-compatible

I am facing a challenge with Tailwind CSS v3+ as it builds colors into the rgb space/color notation that is not compatible with an older browser (Safari 11) that my web app now needs to support. For example, rgb(163 160 158 / var(--tw-bg-opacity) The iss ...

JavaScript - Dynamically loaded CSS: CSS variables are not immediately accessible to JavaScript, but are successfully evaluated within the CSS itself

I am encountering an issue with dynamically loading stylesheets via JavaScript into my application. Within these stylesheets, I have various CSS variables that I need to access and modify from my JavaScript code. When the stylesheets are directly embedded ...