'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'



Solution 1:[1]

If you don't mind changing the context into an asynchronous one you could use fetch() to parse the recourse. fetch() is normally used with URLs, but works with data URIs as well (in most browsers).

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

(async function () {
  const response = await fetch(dataURI);
  const data = await response.json();
  console.log(data);
})();

If you are already using a library to simplify network requests, you could use them as well.

Examples:

jQuery:

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

(async function() {
  const data = await $.getJSON(dataURI);
  console.log(data);
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

axios:

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

(async function() {
  const response = await axios.get(dataURI);
  console.log(response.data);
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.0/axios.min.js"></script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1