是否有任何可以将后表单数据字符串转换为json对象的默认函数?
这是一个例子
sendNotification=true&type=extended&additionalNotes=&returnToMainPage=true
正如您所知,这是POST表单数据的格式。我需要将其转换为JSON对象
{
"sendNotification": "true",
"type": "extended",
"additionalNotes": "",
"returnToMainPage": "true"
}
它也应该处理像这样的数组
blog.blogposts[1].comments 1
blog.blogposts[1].likes 12
我想知道如何使用现有工具和库来实现这一点。我知道我可以编写自己的转换器,但我想应该有一个默认转换器。
由于
重要
我没有表单,我只需转换表单数据字符串。
答案 0 :(得分:1)
试试这个
var params = getUrlVars('some=params&over=here');
console.log(params);
function getUrlVars(url) {
var hash;
var myJson = {};
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
myJson[hash[0]] = hash[1];
}
return myJson;
}
找到了它
答案 1 :(得分:0)
根据Prashanth Reddy的回答,如果你想要json字符串输出,只需在返回时添加JSON.stringify(myJson);
var params = getUrlVars('sendNotification=true&type=extended&additionalNotes=&returnToMainPage=true');
console.log(params);
function getUrlVars(url) {
var hash;
var myJson = {};
var hashes = url.slice(url.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
myJson[hash[0]] = hash[1];
}
return JSON.stringify(myJson);
}
输出:{"sendNotification":"true","type":"extended","additionalNotes":"","returnToMainPage":"true"}
答案 2 :(得分:0)
我这样看
getStringJson('sendNotification=true&type=extended&additionalNotes=&returnToMainPage=true');
function getStringJson(text) {
var json = {}, text = text.split("&");
for (let i in text){
let box = text[i].split("=");
json[box[0]] = box[1];
}
return JSON.stringify(json);
}
生成的输出:
"{"sendNotification":"true","type":"extended","additionalNotes":"","returnToMainPage":"true"}"
答案 3 :(得分:0)
// Form Data String
var dataString = "sendNotification=true&type=extended&additionalNotes=&returnToMainPage=true";
// Split the String using String.split() method. It will return the array.
var params = dataString.split("&");
// Create the destination object.
var obj = {};
// iterate the splitted String and assign the key and values into the obj.
for (var i in params) {
var keys = params[i].split("=");
obj[keys[0]] = keys[1];
}
console.log(obj); // Object {sendNotification: "true", type: "extended", additionalNotes: "", returnToMainPage: "true"}
&#13;