Friday, 14 July 2017

d3.json and Data URLs

I've been playing with d3 quite a bit lately and I know there's a load of stuff I need to learn more about but I thought I'd share this little trick associated with d3.json.

I've had a couple of occasions where I needed to pre-process the json sent to a d3 script. Each time I've been stumped by ds.json requiring an URL, I'm not going to process the data and then send it back to the server in order to get it again, so I started thinking about Data URLs and base64 encoding (as is my wont) and this sorts it out a treat:

let url = "data:application/json;charset=utf-8;base64,";
url += btoa(JSON.stringify(processedObject));
d3.html(url, function(error, graph) {
    if (error) throw error;
    // do cool things with the data...

Anyway, I hope it helps someone (and yes, I do know you don’t need to do it, it’s just nice not to change the original scripts too much!).