0

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
Gumbo
  • 643,351
  • 109
  • 780
  • 844
coure2011
  • 40,286
  • 83
  • 216
  • 349

1 Answers1

2

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
  • 1,311
  • 3
  • 13
  • 26
  • @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 Sep 13 '10 at 11:50
  • @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 Sep 13 '10 at 13:07