0

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

Community
  • 1
  • 1
Jenita
  • 291
  • 1
  • 3
  • 15
  • 4
    `objStr=JSON.parse("'"+objStr+"'"); // puts out unexpected token '` – of course it does, because you _have_ a string value already, so why put additional `'` around it (which just invalidates your JSON)? Just stop that nonsense, and your string will parse perfectly fine. – CBroe Mar 09 '15 at 22:09
  • More specifically, it complains because single quotes aren't even the correct quoting character in JSON! – Alnitak Mar 09 '15 at 22:20
  • Hi, Gosh this is stupid, When I first tried it without the extra single quotes, the string missed some double quotes around its keys. I started looking for the answer and found I had to put extra quotes around it. Okay, you are right it actually does work now. What a waste of my and your time.Thanks – Jenita Mar 09 '15 at 22:23

1 Answers1

2

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);
JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • Thanks, You're right. I just got tangled up with trying all these different things, when at first my String was invalid, and when I fixed that forgot to try the unspoiled version, just passing it the string without quotes – Jenita Mar 09 '15 at 22:28