【发布时间】:2019-08-18 20:08:56
【问题描述】:
我正在使用一个 Google Cloud Platform Function,它侦听 Pub/SubTopic 并将数据插入 BigQuery。
我从 pub/sub 控制台传递的输入数据是 JSON 格式 {"NAME", "ABCD"},但从控制台日志中,我可以看到消息以 {NAME, ABCD} 的形式出现,并且在执行期间,它也会出错。我遇到的 2 个常见错误
SyntaxError: JSON 中的意外标记 n 位于 Export.helloPubSub 的 Object.parse (native) 的位置 1"
“错误:{ 错误:'rows[0].json' 处的值无效”
输入给定:
gcloud pubsub topics publish pubsubtopic1 --message {"name":"ABCD"}
用单引号和方括号以及其他可能的选项尝试了各种格式的输入数据,没有任何帮助
尝试使用 JSON.parse、JSON.stringfy 等解决方法,这有助于避免上面提到的第一个问题,但最终会出现 row[0] 问题
当我将 JSON 输入数据作为{"NAME", "ABCD"} 等云函数中的硬编码值传递时,数据会正确插入。
/**This is working code since i hardcoded the data in JSON format, commented the lines which i tried and did not helped**/
/**
* Triggered from a message on a Cloud Pub/Sub topic.
*
* @param {!Object} event Event payload and metadata.
* @param {!Function} callback Callback function to signal completion.
*/
exports.helloPubSub = (event, callback) => {
const pubsubMessage = event.data;
console.log(Buffer.from(pubsubMessage.data, 'base64').toString());
const {BigQuery} = require('@google-cloud/bigquery');
const bigquery = new BigQuery();
//console.log(Buffer.from(pubsubMessage.data, 'base64').toString());
//console.log(JSON.parse(Buffer.from(pubsubMessage.data, 'base64').toString()));
var myjson='{"NAME":"ABCD","STATE":"HHHH","AGE":"12"}';
console.log(myjson);
bigquery
.dataset("DEMO")
.table("EMP")
.insert(JSON.parse(myjson),
{'ignoreUnknownValues':true, 'raw':false})
//.insert(JSON.parse(Buffer.from(pubsubMessage.data, 'base64').toString()),
.then ((data) => {
console.log('Inserted 1 rows');
console.log(data);
})
.catch(err => {
if (err && err.name === 'PartialFailureError') {
if (err.errors && err.errors.length > 0) {
console.log('Insert errors:');
err.errors.forEach(err => console.error(err));
}
} else {
console.error('ERROR`enter code here`:', err);
}
});
};
【问题讨论】:
标签: google-bigquery google-cloud-functions google-cloud-pubsub