Skip to content

Instantly share code, notes, and snippets.

@gaogao-9
Last active November 21, 2016 10:02
Show Gist options
  • Save gaogao-9/66f508c3db168c4a8b75d92b9dde3b61 to your computer and use it in GitHub Desktop.
Save gaogao-9/66f508c3db168c4a8b75d92b9dde3b61 to your computer and use it in GitHub Desktop.
MapオブジェクトのJSON相互コンバーター(最適化済み)
function mapReviver(key, value){
var len = key.length;
if(len < 5) return value;
if(key.charCodeAt(--len) !== 112) return value;
if(key.charCodeAt(--len) !== 97) return value;
if(key.charCodeAt(--len) !== 109) return value;
if(key.charCodeAt(--len) !== 36) return value;
this[key.slice(0, len)] = new Map(value);
}
function mapReplacer(key, value){
if(!value) return value;
var type = typeof(value);
if(type.length !== 6) return value;
if(type.charCodeAt(0) !== 111) return value;
if(type.charCodeAt(1) !== 98) return value;
if(type.charCodeAt(2) !== 106) return value;
if(type.charCodeAt(3) !== 101) return value;
if(type.charCodeAt(4) !== 99) return value;;
if(type.charCodeAt(5) !== 116) return value;
if(value instanceof Date) return value;
if(value instanceof Array) return value;
if(value instanceof Map) {
var mapIterator = value.entries();
var itrValue, output = [];
while(true){
itrValue = mapIterator.next();
if(itrValue.done) break;
output.push([itrValue.value[0], itrValue.value[1]]);
}
return output;
}
var replacer = Object.create(value);
var keys = Object.keys(value);
for(var i=0,iLen=keys.length,innerValue;i<iLen;++i){
innerValue = value[keys[i]];
if(!(innerValue instanceof Map)){
replacer[keys[i]] = innerValue;
continue;
}
replacer[keys[i]+"$map"] = innerValue;
}
return replacer;
}
var input = `{
"arr": [["key1", "value1"], ["key2", "value2"], ["key3", "value3"]],
"map$map": [["key1", "value1"], ["key2", "value2"], ["key3", "value3"]]
}`;
var json = JSON.parse(input, mapReviver);
console.log("JSON String => JSON Object");
console.log(json);
var jsonStr = JSON.stringify(json, mapReplacer);
console.log("JSON Object => JSON String");
console.log(jsonStr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment