Home > Back-end >  Convert an object to base64 with javascript
Convert an object to base64 with javascript

Time:02-22

I have an object and want to convert this to base64 format to pass in my request's header. For example, this is my object:

const obj = {
key1: 'value1',
key2: 'value2'
}

CodePudding user response:

const object = {
  name:"Harsh",
  age:19
}


// convert object to string using JSON.stringify()

const stringifyObj = JSON.stringify(object)

// convert string to base64

const b64Str = btoa(stringifyObj)

console.log(b64Str)
// convert base64 to original form

const objStr = atob(b64Str)
console.log(objStr)

//  parse objStr to object

const obj = JSON.parse(objStr)
console.log(obj)

Output

eyJuYW1lIjoiSGFyc2giLCJhZ2UiOjE5fQ==
{"name":"Harsh","age":19}
{ name: 'Harsh', age: 19 }

CodePudding user response:

import b64ArrBufferConvertor from 'base64-arraybuffer'

const obj = {
key1: 'value1',
key2: 'value2'
}
const stringifyObj = JSON.stringify(obj)
const binaryObj = new TextEncoder().encode(stringifyObj) 
const base64Obj = b64ArrBufferConvertor.encode(binaryObj)

result = eyJrZXkxIjoidmFsdWUxIiwia2V5MiI6InZhbHVlMiJ9

note: base64-arraybuffer is a library you can install in your project

  • Related