How to convert a query string or map of a JSON object to a separate JSON object using jQuery?

In this example, suppose I have a list of months in a form, each of which has a checkbox next to them. I am looking for help in doing either of two things:

  • Converting a query string (for example, "January=on&March=on&September=on" ) or
  • Object map conversion: [{ January: 'on' },{ March: 'on' },{ September: 'on' }]

for a single JSON object: { January: 'on', March: 'on', September: 'on' }

I understand that the first map is already JSON, but instead of an array of objects, I would like it to be the only JSON object. I can build a map using $('form').serializeArray(); , and I can build the query string using $('form').serialize(); .

Implementing .serialize () in the jQuery API is simple:

 serialize: function() { return jQuery.param(this.serializeArray()); }, 

so I could handle either the first or second answer.

The reason I want to do this is to switch from PrototypeJS to jQuery, and in PrototypeJS it was so simple:

 Object.toJSON(Form.serializeElements($('myform'), true)); 

So, does anyone know of a JSON plugin (I would like to use jQuery ONLY) that could do this easily or know a simple method to achieve the result I'm looking for? Thanks!

+2
source share
5 answers

Kgiannakakis' suggestion for moving around the map was a good starting point, although I do not feel that it qualifies as an answer to my original question. After several hours of giddiness, I decided for this, which allows you to serialize elements based on a user attribute (I did not want to agree to use the "name" attribute in my form elements, which requires jQuery). I also started using the JSON library from json.org to create the object that I am creating. The plugin serializeToJSON function is what I was looking for as an answer to my question, the rest is just exta.

Note This is for the client, so CustomXXX names and attributes have been replaced with what they are actually

 jQuery.fn.extend({ serializeCustomPropertyArray: function() { return this.map(function() { return this.elements ? jQuery.makeArray(this.elements) : this; }).filter(function() { return jQuery(this).attr('CustomAttribute') && (this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password|search/i.test(this.type)); }).map(function(i, elem) { var val = jQuery(this).val(); return val == null ? null : jQuery.isArray(val) ? jQuery.map(val, function(val, i) { return { name: jQuery(elem).attr('CustomAttribute'), value: val }; }) : { name: jQuery(elem).attr('CustomAttribute'), value: val }; }).get(); }, serializeToJSON: function() { var objectMap = this.serializeCustomPropertyArray(); var objectJson = new Object; jQuery.each(objectMap, function() { objectJson[this.name] = (this.value !== null) ? this.value : 'null'; }); return JSON.stringify(objectJson); } }); 

This can be called the following:

 $('#fields').find(':input[CustomGroup="Months"]').serializeToJSON(); 

Assuming your document looks something like this:

 <div id="fields"> <input type="checkbox" CustomGroup="Months" CustomAttribute="January" />January<br /> <input type="checkbox" CustomGroup="Months" CustomAttribute="February" />February<br /> ... </div> 

The generated JSON looks like this:

 { January: 'on', February: 'on', ... } 
+3
source

You can try this

 String.prototype.QueryStringToJSON = function () { href = this; qStr = href.replace(/(.*?\?)/, ''); qArr = qStr.split('&'); stack = {}; for (var i in qArr) { var a = qArr[i].split('='); var name = a[0], value = isNaN(a[1]) ? a[1] : parseFloat(a[1]); if (name.match(/(.*?)\[(.*?)]/)) { name = RegExp.$1; name2 = RegExp.$2; //alert(RegExp.$2) if (name2) { if (!(name in stack)) { stack[name] = {}; } stack[name][name2] = value; } else { if (!(name in stack)) { stack[name] = []; } stack[name].push(value); } } else { stack[name] = value; } } return stack; } 

Query string

  href="j.html?name=nayan&age=29&salary=20000&interest[]=php&interest[]=jquery&interest[1]=python&interest[2]=Csharp&fan[friend]=rangan&fan[family]=sujan&sports[1]=cricket&sports[2]=football"; 

Using

 alert(href.QueryStringToJSON().toSource()) 

conclusion

 ({name:"nayan", age:29, salary:20000, interest:["php", "python", "Csharp"], fan:{friend:"rangan", family:"sujan"}, sports:{1:"cricket", 2:"football"}}) 
+10
source

You can move around the map of objects using $. every function of the utility .

 $(function() { map = [{ January: 'on' },{ March: 'on' },{ September: 'on' }]; $.each(map, function() { $.each(this, function(key, val) {alert(key + " = " + val);});; }); }); 

First of all, you get all the objects in the array. With the second, you can get the key and value of your object.

0
source

I know that you are trying to turn a query string into a JSON object, but it might be interesting for you to go directly from the html form to the JSON object (without specifying really confusing name attributes). If yes, check out JSONForms: http://code.google.com/p/jsonf/

Disclaimer: I started the jsonforms project. He is still young, but personally, I think he is swinging!

0
source

You can also use the parseQuery plugin to create an object from serialized elements.

 var contact = $.parseQuery($("#step1 *").serialize()); 
0
source

Source: https://habr.com/ru/post/902766/


All Articles