简体   繁体   English

从查询字符串参数推断正确的数据类型

[英]Infer correct data type from query string parameters

I'd like to infer the types from parameters of a query string (using Javascript). 我想从查询字符串的参数推断类型(使用Javascript)。

Example URL: 范例网址:

http://example.com/some/path/here/?someString=Hey&someNumber=20

I've used a couple of packages ( query-string and simple-query-string ) like so: 我使用了几个软件包( query-stringsimple-query-string ),如下所示:

queryString.parse(request.url)

Where request.url is the url above. 其中request.url是上面的URL。 This gives the following: 这给出了以下内容:

{
    "someString":"Hey",
    "someNumber":"20"
}

Where someNumber above is type string . 上面的someNumberstring类型。 The desired result is: 理想的结果是:

{
    "someString":"Hey",
    "someNumber":20
}

Where someNumber is type integer . 其中someNumberinteger类型。

The reason I want integer type is because I am performing JSONSchema validation on the parameters which specify the types which are allowed per named parameter. 我想要integer类型的原因是因为我正在对指定每个命名参数允许的类型的参数执行JSONSchema验证。

I am aware that I can cast these instances, but I'd prefer if it was available from a package since it feels a lot like reinventing the wheel. 我知道我可以转换这些实例,但是我更希望它可以从包装中获得,因为它很像是在重新发明轮子。

This should do the trick. 这应该可以解决问题。 You could potentially add more/different regex tests to supplement the simple number check that's in place now (for instance, detect dates, dollar amounts, telephone numbers etc.) 您可能会添加更多/不同的正则表达式测试,以补充当前已进行的简单数字检查(例如,检测日期,美元金额,电话号码等)。

 var exampleurl = "http://example.com/some/path/here/?someString=Hey&someNumber=20" function getQueryStringData(url){ var data = url.split('?')[1].split('&'), numberRgx = /^\\d+(\\.\\d+)?$/ return data.reduce(function(obj, t){ var pair = t.split('='), key = pair[0], val = pair[1] obj[key] = numberRgx.test(val) ? parseFloat(val) : val return obj }, {}) } var obj = getQueryStringData(exampleurl) console.log(obj) document.getElementById('output').textContent = JSON.stringify(obj) 
 <div id="output"></div> 

Here is one method of typecasting an object's properties. 这是一种类型转换对象属性的方法。 if the string itself is one of the special matches in the expression, JSON.parse it, else try Number, else leave it as-is. 如果字符串本身是表达式中的特殊匹配项之一,则JSON.parse,否则尝试Number,否则保持原样。

  function cast (o) {
    var result = {};
    for(var prop in o) { if(o.hasOwnProperty(prop)) {
      var val = o[prop];
      if (typeof val === 'object') return o[prop] = cast(val);
      result[prop] = /^(true|false|null|undefined)$/.test(val) ? JSON.parse(val) : Number(val) || val;
    }}
    return result;
  }

cast( { a: '123', b: 'null', c: 'abc' } ) returns {a: 123, b: null, c: "abc"} cast( { a: '123', b: 'null', c: 'abc' } )返回{a: 123, b: null, c: "abc"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM