0

I receive the below object in my service but when I am parsing this object I get the error

SyntaxError: Unexpected token : in JSON at position 603069

Code:

        var data1 = [];
        // Process a chunk of data. This may be called multiple times.
        req
          .on("data", function(chunk) {
            // Append to buffer
            data1.push(chunk);
          })
          .on("end", function() {
            var buffer = Buffer.concat(data1);
            console.info("Buffer Data Request Body: " + buffer);
            buffer = buffer.toString("utf8");
            var partsOfStr = buffer.split("&");

            //This line gives error
            var obj = JSON.parse(
              decodeURI(buffer.replace(/&/g, '","').replace(/=/g, '":"'))
            );

Object:

{
       "type" : "NewThreadVoice",
       "incidentId": "398115",
       "channel" : "Mobile",
       "data": a huge base 64 string 
       "fileName": "1.aac",
       "contentType" : "aac",
       "contactId" : "954344"
} 

When I reduce the base64 (value of data) to half it works.

Doe
  • 43
  • 1
  • 9
  • 1
    `=` is a valid character in base64 so it's probably part of your base64 string. When you do `.replace(/=/g, '":"')`, you are potentially replacing part of that string, creating something like `"data": "aacasc":"asdasd",`, which is not valid JSON. – Felix Kling Dec 05 '18 at 10:02
  • thnks. It helped – Doe Dec 19 '18 at 07:38

1 Answers1

0

A base64 string is not necessary to contain only one "=" character. This character is used for padding (for more information see Why does a base64 encoded string have an = sign at the end )

For example, the codification of home in base64 is aG9tZQ==. Using your code ( .replace(/=/g, '":"') ), this will be transformed into aG9tZQ":"":"

You should use .replace(/=+/g, '":"') for replacing all consecutive = chars.

banuj
  • 3,080
  • 28
  • 34