<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Love web applications &#187; JSON</title>
	<atom:link href="http://blog.hitsuji.me/tag/json/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.hitsuji.me</link>
	<description>Webアプリつくるの楽しい！つくるネタ、使うネタ、あとは雑談です。</description>
	<lastBuildDate>Sun, 25 Jan 2015 12:49:45 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.1.41</generator>
	<item>
		<title>横浜市地図に数値Dataラベルを貼る</title>
		<link>http://blog.hitsuji.me/add-labels-of-population-values-to-yokohama-city-map/</link>
		<comments>http://blog.hitsuji.me/add-labels-of-population-values-to-yokohama-city-map/#comments</comments>
		<pubDate>Thu, 31 Jul 2014 11:56:37 +0000</pubDate>
		<dc:creator><![CDATA[kapibarawebmaster1515]]></dc:creator>
				<category><![CDATA[可視化]]></category>
		<category><![CDATA[D3.js]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[TopoJSON]]></category>

		<guid isPermaLink="false">http://blog.hitsuji.me/?p=174</guid>
		<description><![CDATA[今日は地図の方を進めようと思います。前回記事「横浜市地図を人口に応じて色塗りする」で描いた地図に、区名ラベルだけでなく数値のラベルも添付できるようにしたいと思います。 &#160; &#160; ポリ・・・<a class="readon" href="http://blog.hitsuji.me/add-labels-of-population-values-to-yokohama-city-map/">続きを読む</a>]]></description>
				<content:encoded><![CDATA[<p>今日は地図の方を進めようと思います。<a title="横浜市地図を人口に応じて色塗りする" href="http://blog.hitsuji.me/show-yokohama-city-map-filled-with-colors-according-to-population/">前回記事「横浜市地図を人口に応じて色塗りする」</a>で描いた地図に、区名ラベルだけでなく数値のラベルも添付できるようにしたいと思います。</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<h3>ポリゴンの中央にラベルを２行を貼付ける</h3>
<p>区毎のポリゴンの中央にラベルが２行くるように位置を調整しつつ、ラベルを貼っていきます。</p>
<p>実際に描いた地図が次の通り（画像をクリックすると地図ページに飛びます）。</p>
<p><a href="http://static.hitsuji.me/map-yokohama09/"><img class="alignnone size-medium_for_2x wp-image-177" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/07/yokohama_map09-436x600.png" alt="yokohama_map09" width="218" height="300" /></a></p>
<p>&nbsp;</p>
<p>やっていることはカンタン。テキストラベルのtransform属性で指定する高さ方向の位置について、上の行は-0.5行、下の行は+0.5行だけシフトさせているだけです。行間は予め決めてあります（labelLineHight）。</p>
<p>&nbsp;</p>
<p>ちなみに・・・<br />
縦方向の座標は下向きが正なので、通常の感覚と逆方向になります。上方向への移動がマイナス，下がプラスですね。</p>
<p>&nbsp;</p>
<p>ソースコードは次の通り。</p>
<h6>index.html</h6>
<script src="https://gist.github.com/b22bcf139ef5c3bed2e6.js"></script><noscript><pre><code class="language-html html">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;ja&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot;&gt;
&lt;script src=&quot;http://d3js.org/d3.v3.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;http://d3js.org/topojson.v0.min.js&quot;&gt;&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
h1 {
    font-size: 16px;
}
svg {
    border: 1px solid #aaaaaa;
}
.subunit-boundary {
  fill: none;
  stroke: #777;
  stroke-dasharray: 2,2;
  stroke-linejoin: round;
}
.cityname-label {
    fill-opacity: .5;
    font-size: 8px;
    font-weight: 300;     
    text-anchor: middle;
    display: none;
}
.stat-label {
    fill-opacity: .5;
    font-size: 8px;
    font-weight: 300;
    text-anchor: middle;
    display: none;
}
&lt;/style&gt;
&lt;title&gt;Yokohama city map&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Yokohama city map&lt;/h1&gt;
&lt;div id=&quot;map&quot;&gt;&lt;/div&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
    
    // file読み込み制御用
    var readTopofileDone = false;
    var readAttrfileDone = false;
    // filedata格納変数
    var topodata;
    var attrdata;
    
    var map_width = 500;
    var map_height = 650;
    var svg;
    
    function readTopofile(json) {
        topodata = json;
        readTopofileDone = true;
    }
    function readAttrfile(json) {
        attrdata = json;
        readAttrfileDone = true;
    }
    
    d3.json(&quot;yokohama_topo_out.json&quot;, function(error, json) {
        if(error) return console.warn(error);
            readTopofile(json);
            if (readTopofileDone &amp;&amp; readAttrfileDone) {
                main(topodata, attrdata);
            }
        });
    
    d3.json(&quot;yokohama_codes_and_stat.json&quot;, function(error, json) {
        if(error) return console.warn(error);
            readAttrfile(json);
            if (readTopofileDone &amp;&amp; readAttrfileDone) {
                main(topodata, attrdata);
            }
        });
    
    function main(topo, attr) {
        
        var labelLineHight = 16;
        // 属性情報を入れ直すためのHash Table
        var attrHash = new Object();
        
        // attr情報を、IDをkeyとするhash-tableに変換する
        // idをKeyとしたhashテーブル＆property毎のhashテーブルを作成する
        attr.forEach(function(e){
            attrHash[e.cityid]=e;
        });
        
        // 人口の最大値と最小値を求めておく
        // --全年齢人口データのみを入れた配列を作成する
        var elements = [];
        var target_key = &quot;ttl&quot;;
        attr.forEach(function(e){
            elements.push(e[target_key]);
        });
        // -- maxとminをとる
        var target_max = Math.max.apply(null, elements);
        var target_min = Math.min.apply(null, elements);
        
         // svgを追加
        svg = d3.select(&quot;body #map&quot;).append(&quot;svg&quot;)
                .attr(&quot;width&quot;, map_width)
                .attr(&quot;height&quot;, map_height);
        
        // 横浜市のmapを描画する
        var yokohama = topojson.object(topo, topo.objects.yokohama);
        console.log(yokohama);
        
        // 横浜市を中心に指定したメルカトル図法で10万分の1で描画する
        var projection = d3.geo.mercator()
                .center([139.59,35.45])
                .scale(100000)
                .translate([map_width / 2, map_height / 2]);
        
        // pathを作成する
        var path = d3.geo.path().projection(projection);
        svg.append(&quot;path&quot;)
          .datum(yokohama)
          .attr(&quot;d&quot;, path);
        
        // classを指定する
        svg.selectAll(&quot;.yokohama&quot;)
            .data(yokohama.geometries)
        .enter().append(&quot;path&quot;)
            .attr(&quot;class&quot;, function(d) {
                return &quot;yokohama &quot; + d.properties.name;
                })
            .attr(&quot;d&quot;, path);
        
        // 色を塗る
        var areaGrad = d3.scale.linear()
                        .domain([target_min, target_max])
                        .range([&quot;#bee59e&quot;, &quot;#349946&quot;]);
        svg.selectAll(&quot;path&quot;).attr(&quot;fill&quot;, &quot;#bee59e&quot;);
        for (var k in attrHash) {
            svg.selectAll(&quot;.&quot;+k).attr(&quot;fill&quot;, areaGrad(attrHash[k][target_key]));
        }
        
        // 内部境界に線を引く
        svg.append(&quot;path&quot;)
           .datum(topojson.mesh(topo, topo.objects.yokohama, function(a, b) { return a !== b; }))
           .attr(&quot;d&quot;, path)
           .attr(&quot;class&quot;, &quot;subunit-boundary&quot;);
        
        // 区コードのラベル貼り
        var city_labels = new Array();
        svg.selectAll(&quot;.cityname-label&quot;)
            .data(yokohama.geometries)
          .enter()
            .append(&quot;text&quot;)
                .attr(&quot;class&quot;, function(d) {
                    if(!(city_labels.indexOf(d.properties.name) &gt; -1)) {
                        city_labels.push(d.properties.name);
                    }
                    return &quot;cityname-label &quot;+d.properties.name; // class名にidを付与
                    })
                .attr(&quot;transform&quot;, function(d) {
                    // 文字をpath中央から、文字高さ1/2分高い位置に貼る
                    var pos = path.centroid(d);
                    pos[1] -= labelLineHight / 2;
                    return &quot;translate(&quot; + pos + &quot;)&quot;;
                })
                .attr(&quot;dy&quot;, &quot;.35em&quot;)
                .text(function(d) {
                    return attrHash[d.properties.name].name;
                });
        
        // 値ラベル貼り
        svg.selectAll(&quot;.stat-label&quot;)
            .data(yokohama.geometries)
          .enter()
            .append(&quot;text&quot;)
                .attr(&quot;class&quot;, function(d) {
                    if(!(city_labels.indexOf(d.properties.name) &gt; -1)) {
                        city_labels.push(d.properties.name);
                    }
                    return &quot;stat-label &quot;+d.properties.name; // class名にidを付与
                    })
                .attr(&quot;transform&quot;, function(d) {
                    // 文字をpath中央から、文字高さ1/2分高い位置に貼る
                    var pos = path.centroid(d);
                    pos[1] += labelLineHight / 2;
                    return &quot;translate(&quot; + pos + &quot;)&quot;;
                })
                .attr(&quot;dy&quot;, &quot;.35em&quot;)
                .text(function(d) {
                    return attrHash[d.properties.name][target_key];
                });
        
        // 各最初のエリアのみラベルを表示する
        for (var i in city_labels) {
            svg.select(&quot;.cityname-label.&quot;+city_labels[i]).style(&quot;display&quot;, &quot;block&quot;);
            svg.select(&quot;.stat-label.&quot;+city_labels[i]).style(&quot;display&quot;, &quot;block&quot;);
        }
        
    }
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre></noscript>
<p>&nbsp;</p>
<p>動けばよし！という感じのコードになってしまいましたが、数値ラベルも合わせて貼れました♪</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>ただ、濃い緑の背景の箇所は黒いテキストラベルが見づらいですね。背景が濃い場合は文字色を白にすると良いのではないでしょうか。</p>
<p>という訳で、次はこの問題を解決すべく、ラベルの色制御をしてみようと思います。</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hitsuji.me/add-labels-of-population-values-to-yokohama-city-map/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>横浜市地図を人口に応じて色塗りする</title>
		<link>http://blog.hitsuji.me/show-yokohama-city-map-filled-with-colors-according-to-population/</link>
		<comments>http://blog.hitsuji.me/show-yokohama-city-map-filled-with-colors-according-to-population/#comments</comments>
		<pubDate>Fri, 25 Jul 2014 02:23:00 +0000</pubDate>
		<dc:creator><![CDATA[kapibarawebmaster1515]]></dc:creator>
				<category><![CDATA[可視化]]></category>
		<category><![CDATA[D3.js]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[map]]></category>
		<category><![CDATA[TopoJSON]]></category>

		<guid isPermaLink="false">http://blog.hitsuji.me/?p=141</guid>
		<description><![CDATA[こんにちは。昨夜の大雨から一転して真夏の気候で大変ですね。外出時には日傘必須です^^; &#160; 地図を人口の大小に応じて色分けする さて、前回の記事「JSONファイルをCSVファイルに変換する」・・・<a class="readon" href="http://blog.hitsuji.me/show-yokohama-city-map-filled-with-colors-according-to-population/">続きを読む</a>]]></description>
				<content:encoded><![CDATA[<p>こんにちは。昨夜の大雨から一転して真夏の気候で大変ですね。外出時には日傘必須です^^;</p>
<p>&nbsp;</p>
<h3>地図を人口の大小に応じて色分けする</h3>
<p>さて、前回の記事「<a title="JSONファイルをCSVファイルに変換する" href="http://blog.hitsuji.me/read-json-conv-2-dimension-list-and-write-it-to-csv/">JSONファイルをCSVファイルに変換する</a>」で作成したJSONファイルを使って、横浜市地図を改めて描きます。行政区毎の人口数の大小に応じて、地図を色塗りします。</p>
<p>&nbsp;</p>
<h4>地図を描画する</h4>
<p>早速完成した地図です♪画像をクリックしてくださいね^^</p>
<p><a href="http://static.hitsuji.me/map-yokohama08/"><img class="alignnone size-medium_for_2x wp-image-142" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/07/yokohama_map08-440x600.png" alt="yokohama_map08" width="220" height="300" /></a></p>
<p>&nbsp;</p>
<p>人口が多い区は濃く、少ない区は薄い色に指定してみました。</p>
<p>&nbsp;</p>
<p>元のソースコードはこちら。</p>
<h6>index.html</h6>
<script src="https://gist.github.com/41e2745f0736ae25bc31.js"></script><noscript><pre><code class="language-html html">&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;ja&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot;&gt;
&lt;script src=&quot;http://d3js.org/d3.v3.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;http://d3js.org/topojson.v0.min.js&quot;&gt;&lt;/script&gt;
&lt;style type=&quot;text/css&quot;&gt;
h1 {
    font-size: 16px;
}
svg {
    border: 1px solid #aaaaaa;
}
.subunit-boundary {
  fill: none;
  stroke: #777;
  stroke-dasharray: 2,2;
  stroke-linejoin: round;
}
.cityname-label {
    fill-opacity: .5;
    font-size: 8px;
    font-weight: 300;     
    text-anchor: middle;
    display: none;
}
&lt;/style&gt;
&lt;title&gt;Yokohama city map&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Yokohama city map&lt;/h1&gt;
&lt;div id=&quot;map&quot;&gt;&lt;/div&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
    
    // file読み込み制御用
    var readTopofileDone = false;
    var readAttrfileDone = false;
    // filedata格納変数
    var topodata;
    var attrdata;
    
    var map_width = 500;
    var map_height = 650;
    var svg;
    
    function readTopofile(json) {
        topodata = json;
        readTopofileDone = true;
    }
    function readAttrfile(json) {
        attrdata = json;
        readAttrfileDone = true;
    }
    
    d3.json(&quot;yokohama_topo_out.json&quot;, function(error, json) {
        if(error) return console.warn(error);
            readTopofile(json);
            if (readTopofileDone &amp;&amp; readAttrfileDone) {
                main(topodata, attrdata);
            }
        });
    
    d3.json(&quot;yokohama_codes_and_stat.json&quot;, function(error, json) {
        if(error) return console.warn(error);
            readAttrfile(json);
            if (readTopofileDone &amp;&amp; readAttrfileDone) {
                main(topodata, attrdata);
            }
        });
    
    function main(topo, attr) {
        
        var labelLineHight = 16;
        // 属性情報を入れ直すためのHash Table
        var attrHash = new Object();
        
        // attr情報を、IDをkeyとするhash-tableに変換する
        // idをKeyとしたhashテーブル＆property毎のhashテーブルを作成する
        attr.forEach(function(e){
            attrHash[e.cityid]=e;
        });
        
        // 人口の最大値と最小値を求めておく
        // --全年齢人口データのみを入れた配列を作成する
        var elements = [];
        var target_key = &quot;ttl&quot;;
        attr.forEach(function(e){
            elements.push(e[target_key]);
        });
        // -- maxとminをとる
        var target_max = Math.max.apply(null, elements);
        var target_min = Math.min.apply(null, elements);
        
         // svgを追加
        svg = d3.select(&quot;body #map&quot;).append(&quot;svg&quot;)
                .attr(&quot;width&quot;, map_width)
                .attr(&quot;height&quot;, map_height);
        
        // 横浜市のmapを描画する
        var yokohama = topojson.object(topo, topo.objects.yokohama);
        console.log(yokohama);
        
        // 横浜市を中心に指定したメルカトル図法で10万分の1で描画する
        var projection = d3.geo.mercator()
                .center([139.59,35.45])
                .scale(100000)
                .translate([map_width / 2, map_height / 2]);
        
        // pathを作成する
        var path = d3.geo.path().projection(projection);
        svg.append(&quot;path&quot;)
          .datum(yokohama)
          .attr(&quot;d&quot;, path);
        
        // classを指定する
        svg.selectAll(&quot;.yokohama&quot;)
            .data(yokohama.geometries)
        .enter().append(&quot;path&quot;)
            .attr(&quot;class&quot;, function(d) {
                return &quot;yokohama &quot; + d.properties.name;
                })
            .attr(&quot;d&quot;, path);
        
        // 色を塗る
        var areaGrad = d3.scale.linear()
                        .domain([target_min, target_max])
                        .range([&quot;#bee59e&quot;, &quot;#349946&quot;]);
        svg.selectAll(&quot;path&quot;).attr(&quot;fill&quot;, &quot;#bee59e&quot;);
        for (var k in attrHash) {
            svg.selectAll(&quot;.&quot;+k).attr(&quot;fill&quot;, areaGrad(attrHash[k][target_key]));
        }
        
        // 内部境界に線を引く
        svg.append(&quot;path&quot;)
           .datum(topojson.mesh(topo, topo.objects.yokohama, function(a, b) { return a !== b; }))
           .attr(&quot;d&quot;, path)
           .attr(&quot;class&quot;, &quot;subunit-boundary&quot;);
        
        // 区コードのラベル貼り
        var city_labels = new Array();
        svg.selectAll(&quot;.cityname-label&quot;)
            .data(yokohama.geometries)
          .enter()
            .append(&quot;text&quot;)
                .attr(&quot;class&quot;, function(d) {
                    if(!(city_labels.indexOf(d.properties.name) &gt; -1)) {
                        city_labels.push(d.properties.name);
                    }
                    return &quot;cityname-label &quot;+d.properties.name; /* class名にidを付与 */
                    })
                .attr(&quot;transform&quot;, function(d) {
                    return &quot;translate(&quot; + path.centroid(d) + &quot;)&quot;;
                })
                .attr(&quot;dy&quot;, &quot;.35em&quot;)
                .text(function(d) {
                    return attrHash[d.properties.name].name;
                });
        
        // 各最初のエリアのみラベルを表示する
        for (var i in city_labels) {
            svg.select(&quot;.cityname-label.&quot;+city_labels[i]).style(&quot;display&quot;, &quot;block&quot;);
        }
        
    }
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code></pre></noscript>
<p>&nbsp;</p>
<p>L.84-93で、区毎の人口数の最大値と最小値を計算しています。</p>
<p><em><span style="color: #808080;">冗長過ぎるコードなので、すっきり直したいですが。</span></em></p>
<p>&nbsp;</p>
<p>L.116-で、各区領域にclass属性を指定しています。</p>
<p>&nbsp;</p>
<p>続いてL.126-で色塗りしています。</p>
<p>D3.jsの機能を使って、色を人口に応じて求める関数を作成します</p>
<pre class="command">areaGrad = d3.scale.linear().domain([target_min, target_max]).range(["#bee59e", "#349946"]);</pre>
<p>d3.scale.linear()は、リニアに補間した結果を返す関数を作成するもので、f = d3.scale.linear()domain([x1, x2]).range([y1, y2])とすると、f(x)は下図のように補間した値yを返してくれます。</p>
<p><img class="alignnone size-large_for_2x wp-image-144" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/07/d3_scale_linear.png" alt="d3_scale_linear" width="600" height="400" /></p>
<p>&nbsp;</p>
<p>さらに、range()には16進数RGB colorも指定できるという優れもので、range([薄い緑, 濃い緑])を指定しました。</p>
<p>domainには、先ほど求めた人口の最小値＆最大値を指定してありますので、</p>
<p><img class="alignnone size-large_for_2x wp-image-145" src="http://blog.hitsuji.me/app/wp-content/uploads/2014/07/d3_scale_linear_ex_2x.png" alt="d3_scale_linear_ex_2x" width="600" height="400" /></p>
<p>&nbsp;</p>
<p>という感じで、L.131でfill指定する色を返してくれます。</p>
<p>&nbsp;</p>
<p>色塗り完成です♪</p>
<p>次回は、人口の数値自体を地図に書き入れる処理を追加したいと思います。</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hitsuji.me/show-yokohama-city-map-filled-with-colors-according-to-population/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JSONファイルをCSVファイルに変換する</title>
		<link>http://blog.hitsuji.me/read-json-conv-2-dimension-list-and-write-it-to-csv/</link>
		<comments>http://blog.hitsuji.me/read-json-conv-2-dimension-list-and-write-it-to-csv/#comments</comments>
		<pubDate>Tue, 22 Jul 2014 12:38:37 +0000</pubDate>
		<dc:creator><![CDATA[kapibarawebmaster1515]]></dc:creator>
				<category><![CDATA[データ処理]]></category>
		<category><![CDATA[CSV]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://blog.hitsuji.me/?p=132</guid>
		<description><![CDATA[こんにちは。梅雨明けしたいも関わらず、ジトジトして不快指数が高いお天気が続きますね。でも湿気に負けないで今日もブログを更新しようと思います！ &#160; さて、今日は以前書いた記事「Perlで横浜市・・・<a class="readon" href="http://blog.hitsuji.me/read-json-conv-2-dimension-list-and-write-it-to-csv/">続きを読む</a>]]></description>
				<content:encoded><![CDATA[<p>こんにちは。梅雨明けしたいも関わらず、ジトジトして不快指数が高いお天気が続きますね。でも湿気に負けないで今日もブログを更新しようと思います！</p>
<p>&nbsp;</p>
<p>さて、今日は<a title="Perlで横浜市の区別年齢別人口データを自動入手する" href="http://blog.hitsuji.me/get-stat-of-yokohama-city-population-automatically/">以前書いた記事「Perlで横浜市の区別年齢別人口データを自動入手する」</a>で入手したJSONファイルをCSVファイルに変換します。何故CSVにしたいかと言えば、<a title="横浜市地図に区名を表示する" href="http://blog.hitsuji.me/show-yokohama-city-map-divided-into-administrative-divisions-with-its-each/">その前に書いた記事「横浜市地図に区名を表示する」</a>で紹介した横浜市地図に人口データを反映させるための情報に編集し直す必要があり、一旦CSVにした方が編集作業が便利そうだからです。</p>
<p>&nbsp;</p>
<h4>JSONファイルを読み込んで、CSVとして書き出す</h4>
<p>横浜市の人口データが入っているJSONファイルを読み込み、２次元テーブルに変換して、CSVとしてファイル出力するスクリプトをPythonで書きました。汎用性のあるコードにしたかったのですが、結構手間取りそうだったので、今回扱うJSONファイルの構造に依存した処理になっています。</p>
<p>&nbsp;</p>
<h6>conv_json_to_csv.py</h6>
<script src="https://gist.github.com/f4fb6867e0ff23a7020a.js"></script><noscript><pre><code class="language-python python">#coding:utf-8
'''
Created on 2014/7/20

@author: Tae Matsumoto
JSONファイルを読み込み、同名のCSVファイルを出力します。
読み込む対象のJSONファイルの構造は下記の通り。
[{'key':区名1, 'stat':{0:0歳人口,1:1歳人口,...}},{'key':区名2, 'stat':{0:0歳人口,1:1歳人口,...}},...]
'''

import csv, json

filename = 'yokohama_stat'

# read json file.
json_data = open(filename+'.json')
data = json.load(json_data)
json_data.close()

res = list()

# add header
tmp = list(data[0]['stat'].items()) + [('key', data[0]['key'])]
tmp.sort()
header = [x[0] for x in tmp]
res.append(header)

# add elements
for row in data:
    row_list = list(row['stat'].items()) + [('key', row['key'])]
    row_list.sort()
    vals = [x[1] for x in row_list]
    res.append(vals)

# display resulsts
print res

# write a file as csv
with open(filename+'.csv', 'wb') as f:
    mywriter = csv.writer(f, delimiter = ',')
    mywriter.writerows(res)
    f.close()
</code></pre></noscript>
<p>&nbsp;</p>
<p>ここではCSVにするためにDictionary型のデータを２次元データに書き換えています。</p>
<p>L32の書き方は便利で、</p>
<pre class="command">[x[1] for x in row_list]</pre>
<p>は、[(x0,y0),(x1,y1),(x2,y2),&#8230;]という形式のリストのうち、第二要素のみを取り出して</p>
<pre class="command">[y0,y1,y2,...]</pre>
<p>と整理してくれます。<a title="how-to-extract-the-n-th-elements-from-a-list-of-tuples-in-python" href="http://stackoverflow.com/questions/3308102/how-to-extract-the-n-th-elements-from-a-list-of-tuples-in-python" target="_blank">=&gt;stackoverflow</a></p>
<p>&nbsp;</p>
<p>以上で、横浜市の0-5歳児の人口データが入ったCSVファイルが出来上がりました。</p>
<p>&nbsp;</p>
<p>次は、<a title="区名と行政団体コードを書き並べたCSVからJSONファイルを作成する" href="http://blog.hitsuji.me/convert-csv-listing-words-name-and-their-codes-to-json/">以前の記事「区名と行政団体コードを書き並べたCSVからJSONファイルを作成する」</a>で作成したCSVファイルと合わせてExcelで編集して次のようにまとめます。</p>
<p>&nbsp;</p>
<script src="https://gist.github.com/d5a9e70d4bcb5671fb3e.js"></script><noscript><pre><code class="language-csv csv">cityid,name,demographics-0,demographics-1,demographics-2,demographics-3,demographics-4,demographics-5,ttlid141011,鶴見区,2712,2875,2812,2589,2518,2525,280234id141020,神奈川区,2037,1960,1971,1916,1736,1812,234496id141038,西区,869,854,809,746,733,692,97251id141046,中区,1112,1150,1052,1081,942,975,147065id141054,南区,1351,1419,1356,1385,1369,1409,194393id141119,港南区,1551,1660,1682,1715,1779,1730,217782id141062,保土ヶ谷区,1432,1469,1485,1542,1444,1492,204290id141127,旭区,1853,1912,1934,2016,2039,1981,248560id141071,磯子区,1261,1360,1280,1257,1314,1363,161968id141089,金沢区,1362,1481,1547,1583,1569,1670,204453id141097,港北区,3455,3294,3122,2885,2758,2721,338969id141135,緑区,1519,1602,1602,1670,1652,1563,178783id141178,青葉区,2614,2780,2644,2777,2766,2812,307844id141186,都筑区,2120,2235,2441,2341,2451,2279,209626id141101,戸塚区,2384,2494,2472,2517,2474,2559,273962id141151,栄区,972,986,1014,972,1004,1018,123176id141160,泉区,1204,1295,1255,1318,1313,1350,154807id141143,瀬谷区,1006,1028,1046,1013,1069,1125,125599</code></pre></noscript>
<p>&nbsp;</p>
<p>これを、同じく<a title="区名と行政団体コードを書き並べたCSVからJSONファイルを作成する" href="http://blog.hitsuji.me/convert-csv-listing-words-name-and-their-codes-to-json/">「区名と行政団体コードを書き並べたCSVからJSONファイルを作成する」</a>で書いたスクリプトを使って、JSONファイルに変換します。</p>
<p>&nbsp;</p>
<p>これで、区名＆人口データが入ったJSONファイルが出来上がりました。</p>
<p>次回はこのファイルを使って、横浜市地図を塗り分けようと思います！</p>
<p>&nbsp;</p>
<p>それでは♪</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.hitsuji.me/read-json-conv-2-dimension-list-and-write-it-to-csv/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
