如何将javascript函数转换为json

How to turn javascript function to json

本文关键字:转换 json 函数 javascript      更新时间:2023-09-26

我正在使用动手表和jsfiddle http://jsfiddle.net/kc11/cb920ear/。其中有以下js函数:

  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'}
    ];
  }

这个数据结构是什么?我可以看到它不是 2d 数组或 json。有没有一种简单的方法可以将其更改为我需要从服务器接收以加载手动表的 json?

要将函数转换为 json do

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

""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 }""给我。请参阅 http://www.kristofdegrave.be/2012/07/json-serialize-and-deserialize.html