1

if there any default functions that can convert a post form data string into json object ?

Here is an example

sendNotification=true&type=extended&additionalNotes=&returnToMainPage=true

As you can this is the format of POST form data. I need to convert it into JSON object

{
    "sendNotification": "true",
    "type": "extended",
    "additionalNotes": "",
    "returnToMainPage": "true"
}

Also it should handle arrays like this

blog.blogposts[1].comments  1
blog.blogposts[1].likes 12

I wonder how can I do this using existing tools and libraries. I know that I can write my own converter, but I guess there should a default one.

Thanks

IMPORTANT

I don't have a form, I need just convert the form data string.

4 Answers4

1

Try this

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;
}

I found it here Convert URL to json

Community
  • 1
  • 1
Prashanth Reddy
  • 197
  • 2
  • 12
1

I see it this way

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);
}

Output generated:

"{"sendNotification":"true","type":"extended","additionalNotes":"","returnToMainPage":"true"}"
shades3002
  • 879
  • 9
  • 11
1

Working Demo

// 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"}
Debug Diva
  • 26,058
  • 13
  • 70
  • 123
0

Building on the answer from Prashanth Reddy, if you want json string output simply add JSON.stringify(myJson); on the return

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);
}

Output: {"sendNotification":"true","type":"extended","additionalNotes":"","returnToMainPage":"true"}

fez
  • 511
  • 1
  • 10
  • 27