SyntaxError:json函数中的意外标识符

时间:2019-05-21 06:02:44

标签: node.js json

我将建立一个从物联网(IoT)设备开始的天气数据管道,利用消息队列接收和传递数据,利用无服务器功能将数据移至数据仓库,然后创建一个显示信息的仪表板。我在功能上出现错误。

/** 
 * Background Cloud Function to be triggered by PubSub. 
 * 
 * @param{  
   object
}event The Cloud Functions event. 
 * @param{  
   function
}callback The callback function. 
 */ 
exports.subscribe = function (event,
callback){  
   const BigQuery = require('@google-cloud/bigquery'); 
  const projectId = "iot2analytics-ca4"; //Enter your project ID here 
  const datasetId = "weatherData"; //Enter your BigQuery dataset name here 
  const tableId = "weatherDatatable"; //Enter your BigQuery table name here -- make sure it is setup correctly 
  const PubSubMessage = event.data; 
  // Incoming data is in JSON format 
  const incomingData = PubSubMessage.data ? Buffer.from(PubSubMessage.data,
   'base64'   ).toString():"{'sensorID':'na','timecollected':'1/1/1970 00:00:00','zipcode':'00000','latitude':'0.0','longitude':'0.0','temperature':'-273','humidity':'-1','dewpoint':'-273','pressure':'0'}"   ;
  const jsonData = JSON.parse(incomingData); 
  var rows =   [  
      jsonData
   ]   ; 

  console.log(`Uploading data:$   {  
      JSON.stringify(rows)
   }   `   ); 

  // Instantiates a client 
  const bigquery = BigQuery(   {  
      projectId:projectId
   }   ); 

  // Inserts data into a table 
  bigquery 
    .dataset(datasetId) 
    .table(tableId) 
    .insert(rows) 
    .then((foundErrors) =>   {  
      rows.forEach((row) => console.log('Inserted:', row)); 

      if (foundErrors && foundErrors.insertErrors != undefined) { 
        foundErrors.forEach((err) => { 
            console.log('      Error:', err); 
        }) 
      } 
    }) 
    .catch((err) => { 
      console.error('      ERROR:',
      err);
   }   ); 
  //   [  
      END bigquery_insert_stream
   ]   callback();
};

1 个答案:

答案 0 :(得分:0)

您正在使用单引号将字符串包装在JSON对象中,这是标准格式所不允许的。请用双引号替换单引号,然后对对象进行字符串化。在这里,使用这个

let temp = {
    "sensorID":"na",
      "timecollected":"1/1/1970 00:00:00",
      "zipcode":"00000",
      "latitude":"0.0",
      "longitude":"0.0",
      "temperature":"-273",
      "humidity":"-1",
      "dewpoint":"-273",
      "pressure":"0"
    }
    temp = JSON.stringify(temp)
    const incomingData = PubSubMessage.data ? Buffer.from(PubSubMessage.data,
       'base64'   ).toString(): temp;