将URL参数转换为JavaScript对象
问题描述:
我有一个这样的字符串:
I have a string like this:
abc = foo& def =%5Basf%5D& xyz = 5
如何将其转换为这样的JavaScript对象?
How can I convert it into a JavaScript object like this?
{
abc: 'foo',
def: '[asf]',
xyz: 5
}
答
编辑
此编辑改进并解释答案基于评论。
Edit
This edit improves and explains the answer based on the comments.
var search = location.search.substring(1);
JSON.parse('{"' + decodeURI(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}')
示例
解析 abc = foo& def =%5Basf%5D& xyz = 5
五步骤:
- decodeURI:abc = foo& def = [asf]& xyz = 5
- 逃脱报价:相同,因为没有报价
- 替换&:
abc = foo,def = [asf],xyz = 5
- 替换=:
abc:foo,def:[asf],xyz:5
- 使用curlies和引号进行描述:
{abc:foo,def:[asf],xyz :5}
- decodeURI: abc=foo&def=[asf]&xyz=5
- Escape quotes: same, as there are no quotes
- Replace &:
abc=foo","def=[asf]","xyz=5
- Replace =:
abc":"foo","def":"[asf]","xyz":"5
- Suround with curlies and quotes:
{"abc":"foo","def":"[asf]","xyz":"5"}
这是合法的JSON。
改进的解决方案允许搜索字符串中包含更多字符。它使用reviver函数进行URI解码:
An improved solution allows for more characters in the search string. It uses a reviver function for URI decoding:
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"}
原始答案
单行:
Original answer
A one-liner:
JSON.parse('{"' + decodeURI("abc=foo&def=%5Basf%5D&xyz=5".replace(/&/g, "\",\"").replace(/=/g,"\":\"")) + '"}')