如何使用Google Apps脚本将JSON文件转换为以换行符分隔的新行? [英] How to convert JSON file to new line delimited using Google Apps Script?
问题描述
我有一个独立的Google Script项目,该项目可从访存URL中生成嵌套的JSON.
iAmOren 的原始代码.
I have a standalone Google Script project that makes nested JSON from fetch URL.
Original code by iAmOren.
function unFlat(fj) {
let date = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd");
var arr=[];
var objL1, objL2, objL3;
var prev_level;
for(var i=0; i<fj.length;i++) {
var obj=fj[i];
switch(Number(obj.level)) {
case 3:
objL3={};
objL3.name=obj.name;
objL3.leads=obj.leads;
objL3.cost=obj.cost;
objL3.revenue=obj.revenue;
objL2.place.push(objL3);
prev_level=3;
break;
case 2:
objL2={};
objL2.path=obj.path;
objL2.name_postfix=obj.name_postfix;
objL2.path_com=obj.path_com;
objL2.name=obj.name;
objL2.place=[];
objL1.partner.push(objL2);
prev_level=2;
break;
case 1:
if(prev_level==3) arr.push(objL1);
objL1={};
objL1.report_date=date;
objL1.name=obj.name;
objL1.partner=[];
prev_level=1;
break;
}
}
if(fj.length) arr.push(objL1);
//Save JSON file on my Drive
let fileSets = {
title: 'JSON_Test.json',
mimeType: 'application/json'
};
let blob = Utilities.newBlob(JSON.stringify(arr), "application/vnd.google-apps.script+json");
Drive.Files.insert(fileSets, blob);
}
它有效,文件出现在我的Google驱动器中.然后,我想将其用作BigQuery的数据集,但它不起作用.
当我尝试将此文件上传到BigQuery时,它返回错误:Failed to create table: Error while reading table: my_json, error message: Failed to parse JSON: No object found when new array is started.; BeginArray returned false; Parser terminated before end of string
.
我认为这是因为我的JSON文件不是用换行符分隔的.
哪里有错,以及如何解决?
It works, file appears in my Google drive. Then I want to use it as data set for BigQuery, but it does not work.
When I try to upload this file to BigQuery it returns an error: Failed to create table: Error while reading table: my_json, error message: Failed to parse JSON: No object found when new array is started.; BeginArray returned false; Parser terminated before end of string
.
I think it is because my JSON file is not new line delimited.
Any way where I'm wrong and how to fix it?
我的JSON文件 >
推荐答案
我自己找到了解决方案
//Save JSON file on my Drive
let fileSets = {
title: 'JSON_Test.json',
mimeType: 'application/json'
};
let blob = Utilities.newBlob(JSON.stringify(arr[0]), "application/vnd.google-apps.script+json"); //modified
Drive.Files.insert(fileSets, blob);
这篇关于如何使用Google Apps脚本将JSON文件转换为以换行符分隔的新行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!