Created
December 22, 2016 03:29
-
-
Save gentamura/58837cb737497db71c0e6920a89e912f to your computer and use it in GitHub Desktop.
重複したkeyを持つJSONデータをカンマ区切りvalueにまとめる ref: http://qiita.com/GenTamura84/items/623bb5d5c5a4bfe58678
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"foo": "ふー", | |
"bar": "ばー", | |
"baz": "ばず", | |
"foo": "フー", | |
"bar": "バー", | |
"baz": "バズ" | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const rs = fs.createReadStream('./duplicate_data.json'); | |
const rl = require('readline'); | |
const rli = rl.createInterface(rs, {}); | |
let pairsAry = []; | |
let pairs = []; | |
let l = ''; | |
// 読み込んだファイルを一行ずつ処理 | |
rli.on('line', (line) => { | |
// 空白、改行を削除 | |
l = line.trim(); | |
// keyとvalueを含めた文字列を配列に分割 | |
pairs = l.split(':'); | |
// "や,など不要な部分を削除して配列を返す | |
pairs = pairs.map((val) => { return val.replace(/\"|\,/g, '').trim(); }); | |
// keyとvalueが存在する配列だけ格納 | |
if (pairs.length === 2) pairsAry.push(pairs); | |
}); | |
let resultObj = {}; | |
// 読み込みが終了したら実行 | |
rli.on('close', () => { | |
let key, value; | |
pairsAry.forEach((val) => { | |
key = val[0]; | |
value = val[1]; | |
if (resultObj.hasOwnProperty(key)) { | |
// すでに同じkeyが存在する場合は、カンマ区切りでvalueを追加 | |
resultObj[key] += ',' + value; | |
} else { | |
// keyが存在しない場合は、新規でvalueをセット | |
resultObj[key] = value; | |
} | |
}); | |
// JSONファイルとして、書き出し | |
fs.writeFile('parsed_data.json', JSON.stringify(resultObj, null, 2)); | |
}); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const data = require('./duplicate_data.json'); | |
console.log(data); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"foo": "ふー,フー", | |
"bar": "ばー,バー", | |
"baz": "ばず,バズ" | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ node parse.js | |
{ foo: 'フー', bar: 'バー', baz: 'バズ' } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment