Serialize HTML form to JSON with pure JavaScript
Solution 2: You can use this lib, is a variant of existing method which, instead of encoding form elements to string, converts form elements to a valid JSON object which can be used in your JavaScript application. This will allow you to define the data that should be exposed, and output in multiple formats such as HTML/Django Template, JSON, XML, or YAML.
Serialize HTML form to JSON with pure JavaScript
I have seen this method of serializing a form to JSON and it’s working fine. My question is: How can I achieve this with pure JavaScript, without using any jQuery code? I am sorry if the question is dumb, but I’m still learning so if anyone can help me, I’ll be grateful.
(function ($) < $.fn.serializeFormJSON = function () < var objects = <>; var anArray = this.serializeArray(); $.each(anArray, function () < if (objects[this.name]) < if (!objects[this.name].push) < objects[this.name] = [objects[this.name]]; >objects[this.name].push(this.value || ''); > else < objects[this.name] = this.value || ''; >>); return objects; >; >)(jQuery);$('form').submit(function (e) < e.preventDefault(); var data = $(this).serializeFormJSON(); console.log(data); /* Object email: "value" name: "value" password: "value" */ >);
P.S. Also in jQuery is this the right way to send multiple JSON objects from user input as One String, because I am searching for a way to do that?
You can try something like this:
function formToJson()< var formElement = document.getElementsByTagName("form")[0], inputElements = formElement.getElementsByTagName("input"), jsonObject = <>; for(var i = 0; i < inputElements.length; i++)< var inputElement = inputElements[i]; jsonObject[inputElement.name] = inputElement.value; >return JSON.stringify(jsonObject); >
This solution works only if you have a single form on the page, to make it more general the function could e.g. take the form element as an argument.
You can use Array.reduce, something like
// get array of all fields and/or selects (except the button) const getFields = () => Array.from(document.querySelectorAll("input, select")) .filter(field => field.type.toLowerCase() !== "button");// get id, name or create random id from field properties const getKey = field => field.name || field.id || `unknown-$`;// get data, simple object const getFormData = () => getFields() .reduce( (f2o, field) => (), <> );// log the result const logResult = txt => document.querySelector("#result").textContent = txt;// get data, array of field objects const getMoreFormData = () => getFields() .reduce( (f2o, field) => f2o.concat( < id: field.id || "no id", name: field.name || "no name", idGenerated: getKey(field), type: field.type, value: field.value >), [] );// handling for buttons document.addEventListener("click", evt => < if (evt.target.nodeName.toLowerCase() === "button") < console.clear(); logResult(/simple/.test(evt.target.textContent) ? JSON.stringify(getFormData(), null, " ") : JSON.stringify(getMoreFormData(), null, " ") ); >> );
Solution 3:
Remember that for checkboxes, value attribute can be either on or off string. This is unwanted. Here is my solution, based on this codepen.
let json = Array.from(form.querySelectorAll('input, select, textarea')) .filter(element => element.name) .reduce((json, element) => < json[element.name] = element.type === 'checkbox' ? element.checked : element.value; return json; >, <>);
let json = <>; Array.from(form.querySelectorAll('input, select, textarea')) .filter(element => element.name) .forEach(element => < json[element.name] = element.type === 'checkbox' ? element.checked : element.value; >);
export type FormJson = ; export const toJson = (form: HTMLFormElement): FormJson => Array.from(form.querySelectorAll('input, select, textarea')) .filter(element => element.name) .reduce((json, element) => < json[element.name] = element.type === 'checkbox' ? element.checked : element.value; return json; >, <>);
Serialize HTML form to JSON with pure JavaScript, Serialize HTML form to JSON with pure JavaScript. Ask Question Asked 3 years, 11 months ago. Modified 1 year, 7 months ago. Viewed 9k times 0 I have seen this method of serializing a form to JSON and it's working fine. My question is: How can I achieve this with pure JavaScript, without using any jQuery …
Serialize form to and from JSON
I want to serialize a form into json, process the json object, then reserialize it to send to a php script via ajax.
Here is a rough example of what I want to do:
s = $('.dia_req_form').serialize(); j = //convert s to json . HOW?? if(j.name) < alert("you must enter a name"); >if(selectedID) < j.id = selectedID; >s = //serialize j . HOW??
You can see the 2 parts that say HOW??
You can use .serializeArray() and $.param() like this:
//validate here var obj = $('.dia_req_form').serializeArray(); if(selectedID) < obj.push(< name: 'id', value: selectedID >); > var s = $.param(obj); //s can be used for submission
Internally, .serialize() is really equivalent to $.param($(this).serializeArray()) , so all this is doing is breaking the steps apart, adding an item if needed.
.serializeArray() is an array of objects with 2 properties ( name and value ), all we're doing is adding some object to the array if needed, then calling $.param() to make it a string.
You can use this lib, $.serializeObject is a variant of existing $.serialize method which, instead of encoding form elements to string, converts form elements to a valid JSON object which can be used in your JavaScript application.
Javascript - How can I *HTML*-encode form contents, The jQuery form .serialize() method serializes form contents to a string and automatically URL-encodes the string.My server then reverses this process and URL-decodes the string when deserializing it. But what I need to be able to do is to HTML-encode the form contents before the form is serialized.In other words, if a …
Python - Serialise HTML and output as JSON
I have a HTML page that displays a few values. I also have a little app that displays data from some other pages I have, but these other pages are JSON, not HTML. I want to consume these values from the HTML page, convert to JSON, then output.
The reason I want to do this is so that I can simply reuse my code, and just change the URL, or even dynamically create it.
I made the HTML page as plain as possible, so as to strip out all the junk in order to make the regex more basic.
BlockABlockBBoth blocks will have varying numbers of elements,depending on a few factors.def index(request, toGet="xyz"): file = urllib2.urlopen("http://www.mysite.com/mypage?data="+toGet) data = file.read() dom = parseString(data) rows = dom.getElementsByTagName("BlockA")[0] readIn = "" for row in rows: readIn = readIn+json.dumps( , sort_keys=True, indent=4)+"," response_generator = ( "["+readIn[:-1]+"]" ) return HttpResponse(response_generator)
So this is basically reading the values (actually, the source is XML in this case), looping through them, and outputting all the values.
If someone can point me in the right direction, it would be much appreciated. For example, reading in the tags like "BlockA" and then the tags "name" and "number".
If you truly need to parse an HTML page in Python, you should be using Beautiful Soup. I question whether you really should be doing this though. Are the HTML pages and JSON outputs using the same Django instance? Are they all apart of the same project?
If they are apart of the same project, then you can use something like django-piston which is a RESTful framework for python. This will allow you to define the data that should be exposed, and output in multiple formats such as HTML/Django Template, JSON, XML, or YAML. You can also create your own emitters to output as a different format.
That way, you can expose a particular URL as a regular template, or get the same data as JSON would will be much easier to parse than HTML.
Sorry if I'm misunderstanding your problem. But it really does sound like you want to expose a view as several different formats, and a RESTful framework will help with that.
Serialize form to json jquery Code Example, Get code examples like "serialize form to json jquery" instantly right from your google search results with the Grepper Chrome Extension.
Serialize html form to JSON without using JQuery
jQuery makes things a lot easir when working with DOM. So many thing there out of the b and you do not need to worry about browsr compatibility.
Browser compatibility used to be a big deal few years back, but not it all comes to almost one engine which is WebKit.
In multimedia advertising on web using jQuery might be not such a good idea. When you do not need a robust behaviour and you tend to have less HTTP requests on your page load, you might re-thing about using jQueryor any other JavaScript framework. In this cse you need to go back to good old, plain JavaScript where there not so many out of the box stuff.
One thing that you will miss is serializing to JSON and using it in AJAX calls. So let's start with the code.
First we transform the form in an array by loping through input fields for form by fetching them by tag name:
function serializeArray(form) < var objects = []; if (typeof form == 'object' && form.nodeName.toLowerCase() == "form") < var fields = form.getElementsByTagName("input"); for(var i=0;i; > > return objects; > No that we did heavy lifting, we can just serilaize it by using simply JSON.Stringify(object) function to get JSON string from object instance:
var dataObject = serializeArray(document.getElementsByTagName('form')[0]); var jsonData = JSON.stringify(dataObject);Now when we have JSON string data we can easity use standard JavaScript objects to make an ajax call without using of any third party library or JavaSvript framework.
function ajaxPost(url, data, callback) < var xmlhttp = new XMLHttpRequest(); if (callback != null && typeof callback !== 'undefined' && typeof callback === 'function') xmlhttp.onreadystatechange = function () < if (this.readyState == 4 && this.status == 200) < callback(this.responseText); >>; xmlhttp.open("POST", url, true); xmlhttp.setRequestHeader("Content-Type", "application/json"); xmlhttp.send(data); >Disclaimer
Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.
About the author
Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform including ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects
CONNECT WITH DEJAN