Created
December 15, 2014 05:00
-
-
Save YusukeHirao/50f741c6bd71ee3024be to your computer and use it in GitHub Desktop.
クエリ文字列をJSONに変換。配列リテラル対応。
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
function queryToJSON (query) { | |
query = query.replace(/^\?/, ''); | |
var knVList = query.split(/&|&/ig); | |
if (!knVList || !knVList[0]) return null; | |
var hash = {}; | |
var knV, key, val; | |
var _a; | |
for (var i = 0; i < knVList.length; i++) { | |
knV = knVList[i].split('='); | |
key = knV[0]; | |
val = decodeURIComponent(knV[1]); | |
// keyがかぶってる場合 | |
if (/\[\]$/.test(key)) { | |
key = key.replace(/\[\]$/, ''); | |
// nameが[]を含む配列形式の場合、そのまま配列へ | |
if (hash[key]) { | |
hash[key].push(val); | |
} else { | |
hash[key] = [val]; | |
} | |
} else if ($.isArray(hash[key])) { | |
hash[key].push(val); | |
} else if (hash[key]) { | |
hash[key] = [hash[key], val]; | |
} else { | |
hash[key] = val; | |
} | |
} | |
return hash; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment