Converting a string to JSON object

Zer0 picture Zer0 · Jun 11, 2012 · Viewed 563.6k times · Source

How do you make JS think that a string is JSON ?

I have a function which only works if JSON object is passed to it. If I pass a string to it, with same format as JSON, it doesn't work. So I want to make that function think that the string passed to it is a JSON. The string is indeed in the JSON format.

I also tried the following. I inputted the string through Ajax , with "handle as" parameter as "JSON", and then when I passed the result to the function it works.

So I deduced the problem is not with the string. How do I convert this string to JSON? If i get same string through ajax request and then passing it to function works, whereas directly passing it doesn't work.

The string is as follows:

  {
     "data": [
   {
  "id": "id1",
      "fields": [
        {
          "id": "name1",
          "label": "joker",
          "unit": "year"
        },
         {"id": "name2", "label": "Quantity"},
    ],
      "rows": [    data here....

and closing braces..

Answer

Kshitij picture Kshitij · Jun 11, 2012
var obj = JSON.parse(string);

Where string is your json string.