Home > front end >  unable to parse json string in node js
unable to parse json string in node js

Time:10-31

I have this below function in which i am calling another function "uploadContentVersion" which is a request POST. This also includes a callback which i am capturing in the below function .

The issue which i am facing is this line "console.log(data)" is giving me result like this

{"id":"11111111111111","success":true,"errors":[]}

But when i am trying to print console.log(data.id) i am getting undefined.Not sure where i am doing wrong.

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);
      });
    }

CodePudding user response:

I dont know what was the issue. I just passed JSON.parse(response.body).id from request and it solved the issue

CodePudding user response:

Your issue appears to be that you are recieving data as a string, not as an Object. In your answer, you responded saying that adding JSON.parse() (mdn) worked. This is because JavaScript interpreters have no way of knowing that you want it treated as an object, so the JSON.parse function was made to fix that. There is also the opposite, JSON.stringify.

  • Related