You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中JSON解析异常:打印data正常但data.id返回undefined

问题:回调中JSON字符串无法访问属性的原因

我编写了异步函数createFileFromJSON,其中调用POST请求函数uploadContentVersion并传入回调。回调中使用console.log(data)可输出JSON格式字符串:{"id":"11111111111111","success":true,"errors":[]},但调用data.id访问属性时返回undefined。

相关代码如下:

const createFileFromJSON = async() => {
    if (fs.existsSync('./templates/officetemplate.docx')) {
      const templateFile = fs.readFileSync('./templates/officetemplate.docx');
      //console.log(templateFile.toString('utf8'))
      var doc = await handler.process(templateFile, data);
      // 3. save output
      fs.writeFileSync('./templates/' + data.accPlanId + '.docx', doc);
      uploadContentVersion(sfdc_token.access_token, sfdc_token.instance_url, data.accPlanId, function(data) {

        var conn = new sf.Connection({});
        conn.initialize({
          instanceUrl: sfdc_token.instance_url,
          accessToken: sfdc_token.access_token
        });
        console.log(data) // 输出:{"id":"11111111111111","success":true,"errors":[]}
        console.log(data.id) // 输出:undefined
        attachFileToRecord(conn, data)
      })
      // console.log(contentversionres)
    } else {
      console.log('Template is not present..')
    }


    var uploadContentVersion = function(token, instUrl, fname, callback) {

      var options = {
        'method': 'POST',
        'url': 'some url',
        'headers': {
          'Authorization': 'Bearer ' + token,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          "VersionData": fs.readFileSync(`./templates/${fname}.docx`).toString('base64')
        })

      };
      request(options, function(error, response) {
        if (response.statusCode === 201) {
          callback(response.body);
        }
        if (error) throw new Error(error);
      });
    }

问题原因

uploadContentVersion函数中传给回调的response.body是JSON格式的字符串,而非JavaScript对象。虽然console.log输出时字符串的外观和对象一致,但它本质还是字符串类型,无法通过.运算符直接访问属性,所以data.id会返回undefined。

解决方案

有两种修复方式:

  1. 在回调内部先解析字符串为对象:
uploadContentVersion(..., function(data) {
  const parsedData = JSON.parse(data);
  console.log(parsedData.id); // 正常输出id值
  attachFileToRecord(conn, parsedData);
})
  1. 在uploadContentVersion的请求回调中提前解析,再传给外部回调:
request(options, function(error, response) {
  if (response.statusCode === 201) {
    callback(JSON.parse(response.body)); // 先解析再传递
  }
  if (error) throw new Error(error);
});

内容的提问来源于stack exchange,提问作者learningmode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 00:02:24