[英]How to convert POST form data to JSON object
是否有任何默认功能可以将邮政表格数据字符串转换为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
我想知道如何使用现有工具和库来执行此操作。 我知道我可以编写自己的转换器,但我想应该有一个默认转换器。
谢谢
重要
我没有表单,我只需要转换表单数据字符串即可。
尝试这个
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;
}
我在这里找到它将URL转换为json
基于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"}
我这样看
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"}"
// 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"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.