1

How to I parse var string = "{email: [email protected]}" into an object?

I've tried var object = JSON.parse(string); which returns an error

Uncaught SyntaxError: Unexpected token e(…)

And var object eval('(' + string + ')'); can't handle '@'.

6
  • Your string isn't valid JSON. What format are you using? Commented Oct 13, 2015 at 17:44
  • JSON.parse isn't working because the email key and the corresponding value need to be strings in order to be valid JSON. If you're just learning JSON, or don't quite have a full grasp on the syntax, try running it through JSONLint, it'll point out errors for you. Commented Oct 13, 2015 at 17:45
  • This would be saying that instead, string should look like: var string = "{'email': '[email protected]'}" ? Commented Oct 13, 2015 at 17:47
  • 1
    @Wesley close, you need to use double quotes and escape them like this: var string = "{\"email\": \"[email protected]\"}" Commented Oct 13, 2015 at 17:50
  • @tcooc I am saving a string to a text file. Imagine the following variable being saved to a .txt doc. var text = JSON.stringify("{" + key + ": " + value + "}"); Commented Oct 13, 2015 at 17:52

3 Answers 3

1

Credit to @iam-decoder -- Check the comments to the initial question for more information.

Two solutions that successfully returned an object for me.

First -- Saving the value as a string with escape characters as follows:
var string = "{\"email\": \"[email protected]\"}"
var result = JSON.parse(string);


Second -- Simply using JSON.stringify for the object instead of building a string, then parsing:
var string = JSON.stringify(object);
var result = JSON.parse(string);

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

Comments

0

Your string cannot be converted into a JavaScript Object because you are using an invalid JSON string. Change

var string = "{email: [email protected]}";

to

var string = '{"email": "[email protected]"}';

or

var string = '{"email": "[email protected]"}';

3 Comments

this is still not valid JSON
Sorry about that, I've changed it.
There we go, much better!
0

You can use this syntax with JSON

var obj = JSON.parse('{"email":"[email protected]"}');

or this one with Eval

var obj = eval('('+'{email:"[email protected]"}'+')');

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.