1

I'm working on a web application witch javascript, and I have to receive and parse a JSON string that looks like this:

{name:"", house:""}

What's the best way to convert it to proper notation?

{"name":"", "house":""}

Thanks in advance!

2
  • 1
    Why do you wanna change it? it seems right until you have special characters in the names/ Commented Nov 10, 2012 at 17:45
  • 2
    If you're receiving a string in that format, it's not JSON. Commented Nov 10, 2012 at 17:48

1 Answer 1

2
var str = '{name:"", house:""}';
var newStr = JSON.stringify( eval( '(' + str + ')' ) );
console.log(newStr); //{"name":"", "house":""}

Fiddle

Do not use eval if the data source is untrusted though.


By the way, are you sure you're receiving a badly formed JSON string and it is not just an object? In case you're using jQuery, it automatically parses JSON responses into objects. In that case you'd just call JSON.stringify passing the object to make a valid JSON string from it, or access the request's responseText. Fiddle with jQuery Ajax.

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

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.