Skip to content
Advertisement

Data URI to JSON in Javascript?

I am facing a problem where my server app gets a JSON’s DataURI and I would like to parse it into a JSON again. How could I do this? I tried different things but nothings seems to work. I tried simply parsing it or encodeURI(data); but still I can’t get the original JSON.

This is the Data URI: data:application/json;base64,ew0KICAgICJtYWx0X3R5cGUiOiAibG9nIiwNCiAgICAibWFsdF9kYXRhIjogIldvdywgdSByIGFsbW9zdCB0aGVyZSA6TyINCn0=

I tried this to encode it too:

var data = 'data:application/json;base64,ew0KICAgICJtYWx0X3R5cGUiOiAibG9nIiwNCiAgICAibWFsdF9kYXRhIjogIldvdywgdSByIGFsbW9zdCB0aGVyZSA6TyINCn0=';
Buffer.from(data.toString('utf8'), 'base64').toString('ascii')

But I get this if I log it on console: u+Zje F- J'm+k0P"&VGEwGR#"&Fvr"@P"&VGEvFF#"%vwrBR"FVw7BFW&R$r P'

Advertisement

Answer

The data URI is JSON encoded in Base64. There are two steps to this:

  1. Decode the Base64 (for instance, with the atob function), and

  2. Parse the resulting JSON

For instance (on a browser):

const dataURI = "data:application/json;base64,ew0KICAgICJtYWx0X3R5cGUiOiAibG9nIiwNCiAgICAibWFsdF9kYXRhIjogIldvdywgdSByIGFsbW9zdCB0aGVyZSA6TyINCn0=";

// 29 = length of "data:application/json;base64,"
const json = atob(dataURI.substring(29));
const result = JSON.parse(json);
console.log(result);

Your use of Buffer in your question suggests to me that you may be using Node.js. If so, you’d replace the call to atob with Buffer.from(data, 'base64').toString():

const dataURI = "data:application/json;base64,ew0KICAgICJtYWx0X3R5cGUiOiAibG9nIiwNCiAgICAibWFsdF9kYXRhIjogIldvdywgdSByIGFsbW9zdCB0aGVyZSA6TyINCn0=";

// 29 = length of "data:application/json;base64,"
const json = Buffer.from(dataURI.substring(29), "base64").toString();
const result = JSON.parse(json);
console.log(result);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement