tags:

views:

109

answers:

1

I am getting a string like this:

var json = "title: abc, link: http://google.com, size: 1";

How can I convert it to an Javascript object so that I can access it like obj.title, obj.link etc. This doesn’t work:

var obj = eval("(" + json + ')');  //error

How to achieve this?

Here is the full code

var entry = json.feed.entry[i];
//here entry = title: abc, link: http://google.com, size: 1
entry = entry.content.$t.replace(/: /g, '": "');
entry = entry.replace(/, /g, '", "');
entry = '"' + entry + '"';

var jdata = eval("(" + entry + ')'); //error: missing ) in parenthetical
+2  A: 

Use the jQuery.parseJSON() And your json string is not valid! You have to doublequote.

var obj = jQuery.parseJSON('{' + '"title": "abc", "link": "http://google.com", "size": 1' + '}');
chriszero
i cannot wrap "" around values. so Your code is not working.
coure06
@coure06: Use the escape character (\) around you're double quotes inside the string, or use single quotes to define the string. His code works fine.
Matt
This guy speaks the truth ^^
Stephen
@Stephen - But the OP is getting malformed JSON as a string, so it's not quite that simple.... take a look at my go at it.
Peter Ajtai