Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert string value to object in Javascript with command similar to eval in Python

In Python stringValue was given as a string variable:

stringValue = '{"DATA":{"VERSION":1.1, "STATE":True, "STATUS":"ONLINE"}}'

I can go ahead and "convert" or "cast" it as Python dictionary using eval built in function:

result = eval(stringValue)

Is there a way to do the same in javascript if we would be given var stringValue as:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var stringValue = '{"DATA":{"VERSION":1.1, "STATE":true, "STATUS":"ONLINE"}}'

>Solution :

use eval

With one caveat … you’ll need to add ( and ) to the string

// this is the ORIGINAL value of the string in the question!!!
var stringValue = "{'DATA':{'VERSION':1.1, 'STATE':true, 'STATUS':'ONLINE'}}";
var result = eval(`(${stringValue})`);
console.log(result)

NOW that you changed the question

and make me look retarded – i.e. swapped ' and " – now you CAN use JSON.parse as a comment suggested

var stringValue = '{"DATA":{"VERSION":1.1, "STATE":true, "STATUS":"ONLINE"}}';
var result = JSON.parse(stringValue);
console.log(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading