0

How can I transform a QueryString like var1=5&var2=stackoverflow&var3=blah to a JSON object like:

{
 "var1": "5",
 "var2": "stackoverflow",
 "var3": "blah"
}

I'm following this, but it looks like I'm missing out something... I can also use jQuery if needed.

Penny Liu
17.9k5 gold badges88 silver badges109 bronze badges
asked Mar 4, 2016 at 5:23
5
  • How exactly does the tutorial code not seem to be working for you? Commented Mar 4, 2016 at 5:25
  • Looks like it's returning an array with the object inside, but I need the object only Commented Mar 4, 2016 at 6:27
  • Did you ever solve this? Was my suggestion able to help you at all? Commented Mar 10, 2016 at 0:11
  • @scniro check my answer... Commented Mar 10, 2016 at 11:06
  • @Napolux your answer doesn't explain a whole lot Commented Mar 11, 2016 at 15:28

5 Answers 5

3

I solved by doing a manual parsing of the object itself...

AjaxForm.prototype.getData = function() {
 var data = this.$element.serializeArray();
 var object = {};
 for (var i = 0; i < data.length; i++) {
 object[data[i].name] = data[i].value;
 }
 return JSON.stringify(object);
};
answered Mar 10, 2016 at 11:08

1 Comment

Can you create a fiddle that shows this working? I don't understand what you are doing here - how are you parsing a query string?
2

Not sure at which point you are struggling with in the mentioned tutorial since you did not provide your snippet, but checking that article out, I was able to craft a fully working example for you (with some improvement suggestions in the comments). Observe the following...

function QueryStringToJSON(str) {
 var pairs = str.split('&');
 var result = {};
 pairs.forEach(function (pair) {
 pair = pair.split('=');
 var name = pair[0]
 var value = pair[1]
 if (name.length)
 if (result[name] !== undefined) {
 if (!result[name].push) {
 result[name] = [result[name]];
 }
 result[name].push(value || '');
 } else {
 result[name] = value || '';
 }
 });
 return (result);
}
var string = 'var1=5&var2=stackoverflow&var3=blah';
var obj = QueryStringToJSON(string);
console.log(obj) // {var1: "5", var2: "stackoverflow", var3: "blah"}

JSFiddle Link - working demo


Searching around on the web will point you to jQuery BBQ: $.deparam as an approach to this at some point. This is great, and probably a bit more robust, but you should be able to get away with the above code first, especially if you desire a vanilla solution (which you always should!!)

answered Mar 4, 2016 at 15:26

1 Comment

You could modify the last line as return (JSON.stringify(result)); This will give the perfect JSON string. Right now its returning an Object will doesn't print in console.log().
2

It could be written in one-liner.

Object.fromEntries(new URLSearchParams('var1=5&var2=stackoverflow&var3=blah'))

Runnable snippet:

const paramsString = "var1=5&var2=stackoverflow&var3=blah";
const searchParams = new URLSearchParams(paramsString);
// Iterate the search parameters.
for (let p of searchParams) {
 console.log(p);
}
console.log(Object.fromEntries(searchParams));

answered May 22, 2020 at 18:03

1 Comment

BEST solution here, not sure why its not upvoted more?
0

You can follow this:

$(function(){
 // Values are not coerced.
 var params = $.deparam.querystring();
 debug.log( 'not coerced', params );
 $('#deparam_string').text( JSON.stringify( params, null, 2 ) );
 // Values are coerced.
 params = $.deparam.querystring( true );
 debug.log( 'coerced', params );
 $('#deparam_coerced').text( JSON.stringify( params, null, 2 ) );
 // Highlight the current sample query string link
 var qs = $.param.querystring();
 $('li a').each(function(){
 if ( $(this).attr( 'href' ) === '?' + qs ) {
 $(this).addClass( 'current' );
 }
 });
});
answered Mar 4, 2016 at 5:31

Comments

0

You can do like this.

var query="var1=5&var2=stackoverflow&var3=blah";
var arr=query.split("&");
result={};
for(i=0;i<arr.length;i++) {
 k = arr[i].split('=');
 result[k[0]] = (k[1] || '');
}; 
console.log(result);

So here what i am doing 1)split query using "&". you will get array as ["var1=5",....];

2)Again splitting every element of array over "=".

3)taking key as arr[0] and value as arr[1] and if no value then ''.

Note:this is for decodeed URI. If URI is encoded first decode it using decodeURIComponent() function.

answered Mar 10, 2016 at 11:29

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.