问题
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);
}
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?
Example of my JSON file
回答1:
Just found solution by myself
//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);
来源:https://stackoverflow.com/questions/62710325/how-to-convert-json-file-to-new-line-delimited-using-google-apps-script