How to (completely) convert a query string to a JSON object?

If I have the following view:

<form> <input name="foo" value="bar"> <input name="hello" value="world"> <input name="animals[]" value="panda"> <input name="animals[]" value="koala"> <input name="car[make]" value="Honda"> <input name="car[origin]" value="Japan"> </form> 

I use not $("form").serialize() :

 foo=bar&hello=world&animals%5B%5D=panda&animals%5B%5D=koalacar&%5Bmake%5D=Honda&car%5Borigin%5D=Japan 

Instead, I want:

 {"foo":"bar", "hello":"world", "animals":["panda", "koala"], "car":{"make":"Honda", "origin":"Japan"}} 

As far as I understand, jQuery used this, but they switched the serialize method to return a GET-style query string. Is there an easy way to get the desired result?


EDIT

I updated my original question to include examples of car[make] and car[origin] . It should be assumed that the input data foo[bar][baz] or foo[bar][baz][bof] may also appear on the form.

In addition, digital indexed keys must be stored, such as foo[0]=a , foo[1]=b , foo[4]=c , for example,

 { ... "foo":["a", "b", undefined, undefined, "c"] ... } 
+6
source share
4 answers

Converting forms to JSON LIKE A BOSS

Github: Follow on on Github

The following code can work with all types of input names; and handle them the way you expected.

eg.

 <!-- all of these will work! --> <input name="honey[badger]" value="a"> <input name="wombat[]" value="b"> <input name="hello[panda][]" value="c"> <input name="animals[0][name]" value="d"> <input name="animals[0][breed]" value="e"> <input name="crazy[1][][wonky]" value="f"> <input name="dream[as][vividly][as][you][can]" value="g"> 
 // output { "honey":{ "badger":"a" }, "wombat":["b"], "hello":{ "panda":["c"] }, "animals":[ { "name":"d", "breed":"e" } ], "crazy":[ null, [ {"wonky":"f"} ] ], "dream":{ "as":{ "vividly":{ "as":{ "you":{ "can":"g" } } } } } } 

Using

 $('#my-form').serializeObject(); 

Witchcraft

 (function($){ $.fn.serializeObject = function(){ var self = this, json = {}, push_counters = {}, patterns = { "validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/, "key": /[a-zA-Z0-9_]+|(?=\[\])/g, "push": /^$/, "fixed": /^\d+$/, "named": /^[a-zA-Z0-9_]+$/ }; this.build = function(base, key, value){ base[key] = value; return base; }; this.push_counter = function(key){ if(push_counters[key] === undefined){ push_counters[key] = 0; } return push_counters[key]++; }; $.each($(this).serializeArray(), function(){ // skip invalid keys if(!patterns.validate.test(this.name)){ return; } var k, keys = this.name.match(patterns.key), merge = this.value, reverse_key = this.name; while((k = keys.pop()) !== undefined){ // adjust reverse_key reverse_key = reverse_key.replace(new RegExp("\\[" + k + "\\]$"), ''); // push if(k.match(patterns.push)){ merge = self.build([], self.push_counter(reverse_key), merge); } // fixed else if(k.match(patterns.fixed)){ merge = self.build([], k, merge); } // named else if(k.match(patterns.named)){ merge = self.build({}, k, merge); } } json = $.extend(true, json, merge); }); return json; }; })(jQuery); 
+9
source

You can use ".serializeArray ()" and then fix the result:

 var json = {}; $.each($('form').serializeArray(), function() { json[this.name] = this.value; }); 

Of course, you can worry about multi-valued fields:

 var json = {}; $.each($('form').serializeArray(), function() { var cur = json[this.name]; if (cur !== undefined) { if ($.isArray(cur)) cur.push(this.value); else json[ this.name.replace(/\[[^\]]*\]$/, '') ] = [ cur, this.value ]; } else json[this.name] = this.value; }); 

(edit - now when I think about it, "serialize" and "serializeArray" are already related to multi-valued parameters for you, giving you names like "independently [2]" in serialized form. 'd work anyway, but it can to be unnecessary to do something more than simple.)

+6
source

I always do that, maybe a little longer, but it's easy for me to maintain.

 function FormContent(foo, hello, animals) { this.Foo = foo; this.Hello = hello; this.Animals = animals; } var animals = []; $("[name='animals[]']").each(function(){ animals.push($(this).val()); }); var foo = $("[name='foo']").val(); var hello = $("[name='hello']").val(); var formContent = new FormContent(foo, hello, animals); var jsonContent = json.stringify(formContent); // from json.org 

I just realized that you specifically asked "use jQuery" sorry. I have never managed to serialize json with jQuery. Hope this helps anyway.

0
source

This is a very good answer for converting a request to JSON. I got the following link fooobar.com/questions/902766 / ...

 knovel.util = { queryParamsToJson : function (theURL) { href = theURL; 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; } } 

Hope this helps someone ...

0
source

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


All Articles