简体   繁体   English

从google电子表格中特定范围的单元格获取json数据

[英]obtaining json data from a specific range of cells in a google spreadsheet

I'm trying to find a way to fetch json data from specific range of cells within a google docs sheet. 我正在尝试找到一种从google文档表中特定范围的单元格中获取json数据的方法。

My spready looks like this 我的大杂烩看起来像这样 在此处输入图片说明

And I would like to obtain a JSON object as follows 我想获得一个JSON对象,如下所示

{ 
 "Parts":{"target1": 230000, "target2":200000},
 "Accessories":{"target1": 150000, "target2":100000},
 "Stars":{"target1": 95, "target2":70},
 "Labour":{"target1": 900, "target2":750},
}

I've read this article and tried to adapt it to my needs, but my experiments in doing so have all been horribly broken. 我已经阅读了这篇文章,并试图使其适应我的需求,但是我这样做的实验都被严重破坏了。 I either end up with a ton of unwanted meta-data in with my json, or nothing at all. 我要么在我的json中放入大量不必要的元数据,要么一无所有。 I suspect the article in question is outdated, being more than 5 years old. 我怀疑相关文章已过时5年,已经过时。

Can anyone suggest a different approach? 有人可以建议其他方法吗?

As you observed, Google Sheets API invariably returns JSON loaded with more metadata than actual content. 如您所见,Google Sheets API始终会返回JSON,该JSON加载的元数据多于实际内容。 To convert a table in the way you want, you need a script. 要以所需的方式转换表,您需要一个脚本。 Here is such a script that can be used as a custom function in sheets: entering =tableJSON(A2:E4) would return the string of desired form. 这是一个可用作工作表中的自定义函数的脚本:输入=tableJSON(A2:E4)将返回所需形式的字符串。

function tableJSON(arr) {
  var i, j, obj = {};
  for (j = 1; j < arr[0].length; j++) {
    obj[arr[0][j]] = {};
  }
  for (i = 1; i < arr.length; i++) {
    for (j = 1; j < arr[0].length; j++) {
      obj[arr[0][j]][arr[i][0]] = arr[i][j];
    }
  }
  return JSON.stringify(obj);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM