我有一个像这样的字符串:
abc=foo&def=%5Basf%5D&xyz=5
如何将其转换为这样的JavaScript对象?
{ abc: 'foo', def: '[asf]', xyz: 5 }
此编辑根据注释改进并解释了答案。
var search = location.search.substring(1); JSON.parse('{"' + decodeURI(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}')
例
abc=foo&def=%5Basf%5D&xyz=5分五个步骤进行解析:
abc=foo","def=[asf]","xyz=5
abc":"foo","def":"[asf]","xyz":"5
{"abc":"foo","def":"[asf]","xyz":"5"}
这是合法的JSON。
一种 改进的解决方案 允许在搜索字符串中包含更多字符。它使用reviver函数进行URI解码:
var search = location.search.substring(1); JSON.parse('{"' + search.replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key===""?value:decodeURIComponent(value) })
search = "abc=foo&def=%5Basf%5D&xyz=5&foo=b%3Dar";
给
Object {abc: "foo", def: "[asf]", xyz: "5", foo: "b=ar"}
单线:
JSON.parse('{"' + decodeURI("abc=foo&def=%5Basf%5D&xyz=5".replace(/&/g, "\",\"").replace(/=/g,"\":\"")) + '"}')