2

I have a JSON object as a string, I am parsing it with JSON.parse() but the resulting object is still a string. Am I doing something wrong?

var myString = "{Username:Brad,Password:12345}";

// adding in the quotes or else it throws an error saying 'unidentified token U
var myJson = JSON.parse('"' + myString + '"');

console.log(myJson.Username); // prints 'undefined'
console.log(typeof(myJson));  // prints 'string'
2
  • 3
    The string is not a valid representation of JSON. The keys and values should be wrapped in quotes. var obj = JSON.parse('{"Username": "Brad","Password": "12345"}'); Use JSONLint to check if your JSON is valid. Commented Jan 11, 2016 at 3:34
  • Thank you, that was the issue. Quotes were there in my client, and for some reason in the response in my server they disapeared. Commented Jan 11, 2016 at 3:40

1 Answer 1

5

That's not valid JSON. keys and strings need to be quoted:

var myString = '{"Username":"Brad","Password":12345}';
var myJson = JSON.parse( myString );

See json.org for information about JSON.

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

1 Comment

Ah ok that works, Thank you! I am using node http module for a server and a client. for some reason during the transit from client to server I am loosing the quotes.

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.