4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

d3.json() 関数を拡張( gzip圧縮された JSON ファイル読込み)

Last updated at Posted at 2017-05-11

こんにちは。
d3.json(file, callback) は、gzip圧縮された JSON ファイル読込みへ対応しないので、代わりの関数を作ってみました(下記のd3_json(file, callback))。これは「gzip圧縮されたローカルファイル読み込み」(gzipd())の応用です。

d3_json.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>d3_json</title>
</head>
<body>
<div id="data"></div>
</body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pako/1.0.11/pako.min.js"></script>
<script src="./getSuffix.js"></script>
<script>
d3_json('employees.json.gz', callback);

function gzipd(xhr) {
    return JSON.parse(pako.inflate(xhr.response, {to: 'string'}));
}

// loading external compressed content
function d3_json(file, callback) { 
    if (getSuffix(file, 'gz')['compression']) {
        d3.request(file).responseType("arraybuffer")
		.response(gzipd).get(callback);
    } else {
        d3.json(file, callback);
    }
}
//  d3.v3: d3.xhr(file)
//  d3.v4: d3.request(file)

function callback(error, data) {
    d3.select('#data')
   .append('div')
   .selectAll()
   .data(data)
   .enter()
   .append('div')
   .text(function (col) {
        return `${col['name']} : ${col['title']} : ${col['age']}`; });
   };
</script>
</html>
getSuffix.js
// extract suffixes from a file name
// e.g., getSuffix('example.json.gz', ['gz', 'bz2']) => {'extension': 'json', 'compression': 'gz'}
function getSuffix(filename, extCompression) {
    var suf = [], fnameSplit = filename.split(".");
    if (fnameSplit.length >= 2) {
        suf.unshift(fnameSplit.pop());
        if (_includes(extCompression, suf[0])) {
           suf.unshift(fnameSplit.pop());
        }
    }
    return {'extension': suf[0], 'compression': suf[1]};
}

function _includes(array, elem) {
    if (!(array instanceof Array)) {array = [array];}
    return array.indexOf(elem) >= 0;
}
$ gzcat employees.json.gz
[
 {"name":"Andy Hunt",
  "title":"Big Boss",
  "age": 68
 },
 {"name":"Charles Mack",
  "title":"Jr Dev",
  "age":24
 }
]
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?