[javascript] JSON string to JS object

I am using a JS object to create graphs with Google visualization. I am trying to design the data source. At first, I created a JS object client-side.

var JSONObject = {
  cols: [{
      id: 'date',
      label: 'Date',
      type: 'date'
    },
    {
      id: 'soldpencils',
      label: 'Sold Pencils',
      type: 'number'
    },
    {
      id: 'soldpens',
      label: 'Sold Pens',
      type: 'number'
    }
  ],
  rows: [{
      c: [{
        v: new Date(2008, 1, 1),
        f: '2/1/2008'
      }, {
        v: 30000
      }, {
        v: 40645
      }]
    },
    {
      c: [{
        v: new Date(2008, 1, 2),
        f: '2/2/2008'
      }, {
        v: 14045
      }, {
        v: 20374
      }]
    },
    {
      c: [{
        v: new Date(2008, 1, 3),
        f: '2/3/2008'
      }, {
        v: 55022
      }, {
        v: 50766
      }]
    }
  ]
};

var data = new google.visualization.DataTable(JSONObject, 0.5);

Now I need to fetch the data dynamically. So I send an AJAX request to a page that returns the JSON string:

 "cols: [{id: 'date', label: 'Date', type: 'date'},
{id: 'soldpencils', label: 'Sold Pencils', type: 'number'},
{id: 'soldpens', label: 'Sold Pens', type: 'number'}],
  rows: [{c:[{v: new Date(2008,1,1),f:'2/1/2008'},{v: 30000}, {v: 40645}]},
      {c:[{v: new Date(2008,1,2),f:'2/2/2008'},{v: 14045}, {v: 20374}]},
{c:[{v: new Date(2008,1,3),f:'2/3/2008'},{v: 55022}, {v: 50766}]}"

This I save into a variable:

var var1 = "cols: [{i ....... 66}]}"

and show as

alert(var1);

Now my task is to create a JS object from this string. This is not working. When I use a JS object, everything works fine and I am able to get my required graph. Now if I try putting the same value of string from the AJAX request which I confirmed from a alert message into a n object, the object is not getting created correctly. Please let me know your opinion and any correction or advices.

This question is related to javascript jquery json jsonp getjson

The answer is


the string in your question is not a valid json string. From json.org website:

JSON is built on two structures:

* A collection of name/value pairs. In various languages, this is 
  realized as an object, record, struct, dictionary, hash table, keyed list, or
  associative array.
* An ordered list of values. In most languages, this is realized as an
  array, vector, list, or sequence.

Basically a json string will always start with either { or [.

Then as @Andy E and @Cryo said you can parse the string with json2.js or some other libraries.

IMHO you should avoid eval because it will any javascript program, so you might incur in security issues.


You can use this library from JSON.org to translate your string into a JSON object.

var var1_obj = JSON.parse(var1);

Or you can use the jquery-json library as well.

var var1_obj = $.toJSON(var1);

The string you are returning is not valid JSON. The names in the objects needs to be quoted and the whole string needs to be put in { … } to form an object. JSON also cannot contain something like new Date(). JSON is just a small subset of JavaScript that has only strings, numbers, objects, arrays, true, false and null.

See the JSON grammar for more information.


You can use eval(jsonString) if you trust the data in the string, otherwise you'll need to parse it properly - check json.org for some code samples.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to jsonp

CORS header 'Access-Control-Allow-Origin' missing JSONP call showing "Uncaught SyntaxError: Unexpected token : " jquery.ajax Access-Control-Allow-Origin Parse JSON response using jQuery parsing JSONP $http.jsonp() response in angular.js How can JavaScript save to a local file? Javascript search inside a JSON object IE9 jQuery AJAX with CORS returns "Access is denied" jquery how to use multiple ajax calls one after the end of the other Callback function for JSONP with jQuery AJAX

Examples related to getjson

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in JQuery get data from JSON array JQuery Parsing JSON array How can I get javascript to read from a .json file? How can I pass request headers with jQuery's getJSON() method? Is it possible to set async:false to $.getJSON call JSON string to JS object load json into variable Error handling in getJSON calls How do I add items to an array in jQuery?