Search code examples
javascriptjsonhandsontable

How to turn javascript function to json


I am working with handsontable and a jsfiddle http://jsfiddle.net/kc11/cb920ear/ . In this there is the following js function:

  function getCarData() {
    return [
      {car: "Mercedes A 160", year: 2006, available: true, comesInBlack: 'yes'},
      {car: "Citroen C4 Coupe", year: 2008, available: false, comesInBlack: 'yes'},
      {car: "Audi A4 Avant", year: 2011, available: true, comesInBlack: 'no'},
      {car: "Opel Astra", year: 2004, available: false, comesInBlack: 'yes'},
      {car: "BMW 320i Coupe", year: 2011, available: false, comesInBlack: 'no'}
    ];
  }

What is this data structure is this? I can see its not a 2d array or json. Is there an easy way to change it to json which I will need to receive from a server to load the handsontable?


Solution

  • To turn a function into json do

    JSON.stringify(getCarData, function(key, value) {
      if (typeof value === 'function') {
        return value.toString();
      }
      return value;
    });
    

    returned ""function getCarData() {\n return [\n {car: \"Mercedes A 160\", year: 2006, available: true, comesInBlack: 'yes'},\n {car: \"Citroen C4 Coupe\", year: 2008, available: false, comesInBlack: 'yes'},\n {car: \"Audi A4 Avant\", year: 2011, available: true, comesInBlack: 'no'},\n {car: \"Opel Astra\", year: 2004, available: false, comesInBlack: 'yes'},\n {car: \"BMW 320i Coupe\", year: 2011, available: false, comesInBlack: 'no'}\n ];\n }"" to me. See http://www.kristofdegrave.be/2012/07/json-serialize-and-deserialize.html