是否有一个快速和简单的方法来编码JavaScript对象到字符串,我可以通过GET请求传递?
没有jQuery,没有其他框架-只有纯JavaScript:)
是否有一个快速和简单的方法来编码JavaScript对象到字符串,我可以通过GET请求传递?
没有jQuery,没有其他框架-只有纯JavaScript:)
当前回答
这是对已接受的解的补充。这适用于对象和对象数组:
parseJsonAsQueryString = function (obj, prefix, objName) {
var str = [];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
var v = obj[p];
if (typeof v == "object") {
var k = (objName ? objName + '.' : '') + (prefix ? prefix + "[" + p + "]" : p);
str.push(parseJsonAsQueryString(v, k));
} else {
var k = (objName ? objName + '.' : '') + (prefix ? prefix + '.' + p : p);
str.push(encodeURIComponent(k) + "=" + encodeURIComponent(v));
//str.push(k + "=" + v);
}
}
}
return str.join("&");
}
我还添加了objName,如果你使用对象参数,像在ASP。NET MVC动作方法。
其他回答
如果您想递归地转换嵌套对象,并且对象可能包含也可能不包含数组(数组可能包含对象或数组等),那么解决方案就会变得稍微复杂一些。这就是我的尝试。
我还添加了一些选项,用于选择是否要为每个对象成员记录它位于主对象中的深度,以及选择是否要向来自已转换数组的成员添加标签。
理想情况下,您应该测试thing参数是否真的接收到对象或数组。
function thingToString(thing,maxDepth,recordLevel,markArrays){
//thing: object or array to be recursively serialized
//maxDepth (int or false):
// (int) how deep to go with converting objects/arrays within objs/arrays
// (false) no limit to recursive objects/arrays within objects/arrays
//recordLevel (boolean):
// true - insert "(level 1)" before transcript of members at level one (etc)
// false - just
//markArrays (boolean):
// insert text to indicate any members that came from arrays
var result = "";
if (maxDepth !== false && typeof maxDepth != 'number') {maxDepth = 3;}
var runningDepth = 0;//Keeps track how deep we're into recursion
//First prepare the function, so that it can call itself recursively
function serializeAnything(thing){
//Set path-finder values
runningDepth += 1;
if(recordLevel){result += "(level " + runningDepth + ")";}
//First convert any arrays to object so they can be processed
if (thing instanceof Array){
var realObj = {};var key;
if (markArrays) {realObj['type'] = "converted array";}
for (var i = 0;i < thing.length;i++){
if (markArrays) {key = "a" + i;} else {key = i;}
realObj[key] = thing[i];
}
thing = realObj;
console.log('converted one array to ' + typeof realObj);
console.log(thing);
}
//Then deal with it
for (var member in thing){
if (typeof thing[member] == 'object' && runningDepth < maxDepth){
serializeAnything(thing[member]);
//When a sub-object/array is serialized, it will add one to
//running depth. But when we continue to this object/array's
//next sibling, the level must go back up by one
runningDepth -= 1;
} else if (maxDepth !== false && runningDepth >= maxDepth) {
console.log('Reached bottom');
} else
if (
typeof thing[member] == "string" ||
typeof thing[member] == 'boolean' ||
typeof thing[member] == 'number'
){
result += "(" + member + ": " + thing[member] + ") ";
} else {
result += "(" + member + ": [" + typeof thing[member] + " not supported]) ";
}
}
}
//Actually kick off the serialization
serializeAnything(thing);
return result;
}
const buildSortedQuery = (args) => { 返回种(args) .sort () .map(key => { 返回window.encodeURIComponent(关键) + ' = ' + window.encodeURIComponent (args(例子)); }) . join (' & '); }; console.log (buildSortedQuery ({ Foo:“你好”, 栏:“100%” })); / /酒吧= 100% 25 foo =你好% 20
单行转换对象为查询字符串,以防有人再次需要它:
let Objs = { a: 'obejct-a', b: 'object-b' }
Object.keys(objs).map(key => key + '=' + objs[key]).join('&')
// The result will be a=object-a&b=object-b
使用Node.js v6.6.3
const querystring = require('querystring')
const obj = {
foo: 'bar',
baz: 'tor'
}
let result = querystring.stringify(obj)
// foo=bar&baz=tor
参考:查询字符串
对用户187291接受的解决方案的一个小修改:
serialize = function(obj) {
var str = [];
for(var p in obj){
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
}
return str.join("&");
}
检查对象上的hasOwnProperty使JSLint和JSHint高兴,它防止意外序列化对象的方法或其他东西,如果对象不是一个简单的字典。有关JavaScript编程语言的代码约定的语句,请参阅上一段。