【问题标题】:How to turn javascript function to json如何将javascript函数转换为json
【发布时间】:2015-02-27 19:59:41
【问题描述】:

我正在使用 handontable 和 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'}
    ];
  }

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

【问题讨论】:

  • 在我看来就像一个二维数组,包含对象?
  • 除了JSON.stringify()?
  • 您需要对这个数组做什么确切handsontable 期待什么?我认为不需要将其转换为 JSON 字符串。您只需将其转换为handsontable 可以使用的格式,我假设它是一个数组或对象,而不是 JSON 字符串。
  • 对不起,我回去再看一遍,发现我看错了stackoverflow.com/questions/4329092/…,它确实是一个二维数组或对象数组
  • Rocket,我想将 getCarData() 中的示例数据更改为 json,这样我就可以模拟一个 db 后端,该后端生成 json 供 handsontable 使用。

标签: javascript json handsontable


【解决方案1】:

把函数转成json做

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

【讨论】:

  • 不应该是JSON.stringify(getCarData())吗?您为什么要尝试将 function 本身转换为 JSON?他想操纵那个函数的返回值
  • 另外,它不是“json对象”数组。它是 [JavaScript] 对象的数组。 JSON 是数据的字符串表示;如果不是字符串,则不是 JSON。
  • 错误的问题标题是“如何将 javascript 函数转换为 json”,所以我展示了如何将他的函数转换为 json 字符串。
  • 同样JSON.stringify(<function>) 将返回未定义。因此需要上面提供的回调。
  • 啊,我看到你将执行函数的结果传递给 JSON.stringify。这会将结果字符串化,但不会序列化函数。取决于你真正想要什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-24
  • 1970-01-01
  • 1970-01-01
  • 2018-12-04
相关资源
最近更新 更多