-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
5
  • stackoverflow.com/questions/45015/… Commented Sep 13, 2010 at 11:12
  • 3
    This isn't valid JSON, so you are going to get an error unless you can fix that first. Commented Sep 13, 2010 at 11:49
  • its just an example, the point is i am getting json string from somewhere else so i cannot wrap "" around it. Commented Sep 13, 2010 at 11:51
  • 1
    Is is really valid JSON or is it just JSON-like? Commented Sep 13, 2010 at 12:20
  • There is little JSON-like about it. Commented Jul 13, 2024 at 8:21

1 Answer 1

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' + '}');
Sign up to request clarification or add additional context in comments.

2 Comments

@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.
@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.

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.