Reputation: 291
I have a problem parsing a string variable back to an object.I have looked at all other question around this topic but none solve my problem.
if(subMatch.match(/\{.*\}/)){ /// new Object of some sort
var objStr=subMatch.match(/\{.*\}/)[0];
//objStr= JSON.stringify(objStr); // I tried this , no difference
//objStr='"'+objStr+'"'; // Tried this way: unexpected token t
//objStr="'"+objStr+"'"; // Tried this way: unexpected token '
objStr=JSON.parse("'"+objStr+"'"); // puts out unexpected token '
This is the string I am trying it out on:
{"type": "lawnmowing","hours": 10,"rate": 10.5,"permanent": false}
According to JSONLint it is valid. With the extra quotes it looks like:
'{"type": "lawnmowing","hours": 10,"rate": 10.5,"permanent": false}'
I looked at this question,
JSON.Parse,'Uncaught SyntaxError: Unexpected token o
but their variable starts as an object. My objStr has type String, I checked. I am adding literal single quotes around objStr. Because objStr is already a String, that should not be a problem right? I've also tried completely without extra quotes around the variable
How can I correctly JSON.parse a String variable. I can get it to work with eval, but I rather not use that, because it is user input that I have to put in an object.
Sorry to bother you with a question about this topic again, but I haven't found the solution among the other questions.
Help would be really appreciated! Thanks Jenita
Upvotes: 0
Views: 1830
Reputation: 101690
As CBroe says, JSON.parse()
can parse JSON just fine on its own and whatever you're trying to do here is preventing it from doing that.
It doesn't need your help. Just let it do its job and get rid of all that mess:
var obj = JSON.parse(objStr);
Upvotes: 2