1

I am trying to create an object out of string which is not a typical JSON string.

Here is the example:

 var ObjectInString = "{x:62.43993,y:293.64093}"; //string i want to turn into an object
var ObjectWhichWorks = {x:62.43993,y:293.64093};

console.log(ObjectInString);
console.log(ObjectWhichWorks);

11
  • Use JSON.parse(string) to convert string to object Commented May 7, 2017 at 20:38
  • 1
    Are you having the same problem as described here? If so, this is a duplicate. If not, please explain why. Commented May 7, 2017 at 20:41
  • Solution to this question does not work for me. Commented May 7, 2017 at 20:44
  • Try JSON.parse(JSON.stringify(ObjectInString)) Commented May 7, 2017 at 20:46
  • I need to have the same output as is given on object in snipped. Commented May 7, 2017 at 20:46

3 Answers 3

1

You can use eval to interpret a JavaScript expression inside of a string. We need to wrap this value in parentheses for it to be parsed properly as an object literal, instead of an invalid statement.

var ObjectInString = "{x:62.43993,y:293.64093}";
var Object = eval("(" + ObjectInString + ")");

console.log(ObjectInString);
console.log(Object);

However, using eval with untrusted data is a massive security vulnerability. Only do this with data from sources that are entirely trusted, and look for alternatives (such as using valid JSON data you can parse with JSON.parse(...) as soon as possible.

Sign up to request clarification or add additional context in comments.

Comments

0

Assuming your keys are always x and y, convert the string to a valid JSON string by adding double quotes around those keys. You can then use JSON.parse() to get the desired object:

var o = '{x:62.43993,y:293.64093}';

console.log(JSON.parse(o.replace('x', '"x"').replace('y', '"y"')));

Comments

0

many years ago i search alot for this solution.

var obj = eval ("(" + ObjectInString + ")");

i don't know about cross browser support or anything else, just know it work for me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.