Home > OS >  base64 is incorrect. how to convert json to correct base64?
base64 is incorrect. how to convert json to correct base64?

Time:12-30

I want to convert this json to base64 using Javascript/Nodejs. But it is not giving me correct output?

My JSON object:

const templates = [
  {
    "name": "next-hover-base",
  },
  {
    "name": "next-hover-base",
  },
];

const inBase64Format = Buffer.from(JSON.stringify(templates)).toString("base64");
console.log(inBase64Format);

It's output is:

W3sibmFtZSI6Im5leHQtaG92ZXItYmFzZSJ9LHsibmFtZSI6Im5leHQtaG92ZXItYmFzZSJ9XQ==

But when I convert above json object to base64 online from https://onlinejsontools.com/convert-json-to-base64

It's output is:

WwogIHsKICAgICJuYW1lIjogIm5leHQtaG92ZXItYmFzZSIsCiAgfSwKICB7CiAgICAibmFtZSI6ICJuZXh0LWhvdmVyLWJhc2UiLAogIH0sCl0=

I want to convert above JSON to base64 and want 2nd output in Javascript/Nodejs.

How can I get 2nd output with whitespaces and linebreaks?

CodePudding user response:

The second one includes a prettified version. to emulate it pass the desired indentation (2 in your case) to the JSON.stringify method space argument:

const templates = [
  {
    "name": "next-hover-base",
  },
  {
    "name": "next-hover-base",
  },
];

const inBase64Format  = btoa(JSON.stringify(templates));
const inBase64Format2 = btoa(JSON.stringify(templates, null, 2)); // 2 spaces indentation

console.log(inBase64Format);
// W3sibmFtZSI6Im5leHQtaG92ZXItYmFzZSJ9LHsibmFtZSI6Im5leHQtaG92ZXItYmFzZSJ9XQ==
console.log(inBase64Format2);
// WwogIHsKICAgICJuYW1lIjogIm5leHQtaG92ZXItYmFzZSIsCiAgfSwKICB7CiAgICAibmFtZSI6ICJuZXh0LWhvdmVyLWJhc2UiLAogIH0sCl0=

  • Related