[英]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.