[英]How do I convert a couple of Google Sheets columns into a JSON string?
I'm working on a piece of code that will convert two columns (A, B) into key/value pairs with JSON formatting.我正在编写一段代码,它将两列 (A, B) 转换为具有 JSON 格式的键/值对。 I can't figure out how to make it work.我不知道如何使它工作。 I currently have a function that will read the top row (keys) and the bottom row of the values, but I can't get it to show the rows in between.我目前有一个函数可以读取值的顶行(键)和底行,但我无法让它显示中间的行。 I'm not an engineer or a developer, but I do enjoy coding.我不是工程师或开发人员,但我喜欢编码。
The sheet looks like this:该表如下所示:
+-------+-------------+ | A | B | +-------+-------------+ | code | description | +-------+-------------+ | brand | microsoft | +-------+-------------+ | size | large | +-------+-------------+ | color | green | +-------+-------------+
And I'm expecting to get a JSON string like this:我期待得到这样的 JSON 字符串:
[{"code":"brand","description":"microsoft"}, {"code":"color","description":"green"}, {"code":"size","description":"large"}]
So far my Google Apps Script code looks like this:到目前为止,我的 Google Apps 脚本代码如下所示:
function tableJSON(arr) {
var i, j, obj = {};
for (j = 0; j < arr[0].length; j++) {
obj[arr[0][j]] = {};
}
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr[0].length; j++) {
obj[arr[0][j]] = arr[i][j];
}
}
return JSON.stringify(obj);
}
And the result when I type当我输入时的结果
="[" & tableJSON(A1:B4) & "]"is: 是:
[{"code":"size","description":"large"}] [{"code":"size","description":"large"}]
I'm sure the solution is simple, but I haven't been able to figure it out.我确信解决方案很简单,但我一直无法弄清楚。
The code only creates 1 object and rewrites the same object each time in iteration.该代码仅创建 1 个对象并在每次迭代中重写相同的对象。
/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/ /** * @param{Array<Array>} arr 2D array * @customfunction * @OnlyCurrentDoc */ function tableJSONFixed(arr) { 'use strict'; const [code, desc] = arr.shift(); return JSON.stringify(arr.map(([v1, v2]) => ({ [code]: v1, [desc]: v2 }))); } console.info( tableJSONFixed([ ['code', 'description'], ['brand', 'google'], ['size', 'large'], ['color', 'green'], ]) );
<!-- https://meta.stackoverflow.com/a/375985/ --> <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
https://github.com/jsoma/tabletop https://github.com/jsoma/tabletop
I was using tabletop to convert sheets to JSON but if you have an organisational google account this isn't going to work for much longer我正在使用桌面将工作表转换为 JSON,但如果您有一个组织的 google 帐户,这将不会工作太久
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.