How To Format Form Data as JSON (2023)

The browser Fetch API is used to make requests from a web page on the frontend to an API endpoint on the backend.

On the other hand, the browser FormData API provides a precise way of accessing HTML form fields. These two native support browser APIs make it easy to send requests. Yet to send data as JSON to an API endpoint this requires extra work. In this tutorial, we will explore a step by step procedure on how to capture form field data, format them as JSON data and send it to an API endpoint.

Table of contents

  • Prerequisites
  • The HTML form template
  • Listening for the form submission
  • Reading the form field values with the FormData API
  • Formating data to JSON and making a POST request
  • The complete code
  • Handling JSON request body in a Nodejs and Express.js API
  • Conclusion

Prerequisites

To follow along with this tutorial a basic knowledge of the following is required:

By the end of this tutorial, you should have a working HTML form that sends form data as JSON to an API endpoint. In the process, you will learn how to make use of the native browser Fetch and FormData APIs to achieve this goal. In the end, you will have a simple Express Node.js API which will listen for the request you send and send back the response.

The HTML form template

<form id="sample-form" method="post" action="http://localhost:5500/form"> <h1>Sample Form</h1> <section> <fieldset> <h3>Gender</h3> <ul> <li> <label for="gender_1"> <input type="radio" id="gender_1" name="gender" value="Male" /> Male </label> </li> <li> <label for="gender_2"> <input type="radio" id="gender_2" name="gender" value="Female" /> Female </label> </li> </ul> </fieldset> <p> <label for="user-fullname"> <span>Full Name: </span> <strong><abbr title="required">*</abbr></strong> </label> <input type="text" id="user-fullname" name="username" /> </p> <p> <label for="user-mail"> <span>E-mail: </span> <strong><abbr title="required">*</abbr></strong> </label> <input type="email" id="user-mail" name="usermail" /> </p> <p><button type="submit">Submit Form</button></p> </section></form>

How To Format Form Data as JSON (1)

Here we have a form with 2 radio buttons for selecting male or female gender and 2 input fields, for the full name and email address and a button to submit the form.

Listening for the form submission

Getting the form by ID.

//Get the form element by idlet sampleForm = document.getElementById("sample-form");

When the form’s submit button is clicked the browser dispatches an event, which is captured by the form’s submit event listener. Define the event handler for the form when it’s submitted and prevent the default browser behaviour so that you can handle it instead.

(Video) How to Convert HTML Form Data to JSON Object

//Define the event handler for the form when it's submittedsampleForm.addEventListener("submit", async (e) => { //Prevent browser default behavior e.preventDefault(); // More code here in the next step}

Reading the form field values with the FormData API

The FormData API provides a precise way of accessing the HTML form field values by passing it a reference to the form element by getting the element attached to the event handler. Then get the URL from the form’s action attribute.

This obtains all the form fields and makes the form field values available as key-value pairs through a FormData instance. Then call the postFormFieldsAsJson() function (define it in the next step) and pass the url and the formData instance as arguments.

//Define the event handler for the form when it's submittedsampleForm.addEventListener("submit", async (e) => { //Prevent browser default behavior e.preventDefault(); //Get the entire form fields let form = e.currentTarget; //Get URL for api endpoint let url = form.action; try { //Form field instance let formFields = new FormData(form); //Call the `postFormFieldsJson()` function let responseData = await postFormFieldsAsJson({ url, formFields }); } catch (error) { // Handle the error here. console.error(`An has occured ${error}`); }}

Formating data to JSON and making a POST request

Passing the FormData instance directly to fetch by default, the request body is formatted as “multipart” and the Content-Type on the request header is set to multipart/form-data. Convert the FormData instance to a plain object and then into a JSON string.

Create an object from the formData instance using the Object.fromEntries() method.

Using the JSON.stringify() method then format the plain form data as JSON.

Specify the HTTP request method as POST and using the header field of the Fetch API specify that you are sending a JSON body request and accepting JSON responses back.

Then set the request body as JSON created from the form fields. Now send the request and listen for the response. If the response is OK return the response body, otherwise throw an error.

/** * Helper function to POST data as JSON with Fetch. */async function postFormFieldsAsJson({ url, formData }) { //Create an object from the form data entries let formDataObject = Object.fromEntries(formData.entries()); // Format the plain form data as JSON let formDataJsonString = JSON.stringify(formDataObject); //Set the fetch options (headers, body) let fetchOptions = { //HTTP method set to POST. method: "POST", //Set the headers that specify you're sending a JSON body request and accepting JSON response headers: { "Content-Type": "application/json", Accept: "application/json", }, // POST request body as JSON string. body: formDataJsonString, }; //Get the response body as JSON. //If the response was not OK, throw an error. let res = await fetch(url, fetchOptions); //If the response is not ok throw an error (for debugging) if (!res.ok) { let error = await res.text(); throw new Error(error); } //If the response was OK, return the response body. return res.json();}
(Video) Post Form Data as JSON with Fetch API using JavaScript | HTML Form to JSON

The complete code

This is the full JavaScript code with inline comments from the steps above that:Captures the form fields using the browser FormData API, converts them to JSON and finally send them to an API endpoint using the browser Fetch API.

//Get the form element by idconst sampleForm = document.getElementById("sample-form");//Add an event listener to the form element and handler for the submit an event.sampleForm.addEventListener("submit", async (e) => { /** * Prevent the default browser behaviour of submitting * the form so that you can handle this instead. */ e.preventDefault(); /** * Get the element attached to the event handler. */ let form = e.currentTarget; /** * Take the URL from the form's `action` attribute. */ let url = form.action; try { /** * Takes all the form fields and make the field values * available through a `FormData` instance. */ let formData = new FormData(form); /** * The `postFormFieldsAsJson()` function in the next step. */ let responseData = await postFormFieldsAsJson({ url, formData }); //Destructure the response data let { serverDataResponse } = responseData; //Display the response data in the console (for debugging) console.log(serverDataResponse); } catch (error) { //If an error occurs display it in the console (for debugging) console.error(error); }});/** * Helper function to POST data as JSON with Fetch. */async function postFormFieldsAsJson({ url, formData }) { //Create an object from the form data entries let formDataObject = Object.fromEntries(formData.entries()); // Format the plain form data as JSON let formDataJsonString = JSON.stringify(formDataObject); //Set the fetch options (headers, body) let fetchOptions = { //HTTP method set to POST. method: "POST", //Set the headers that specify you're sending a JSON body request and accepting JSON response headers: { "Content-Type": "application/json", Accept: "application/json", }, // POST request body as JSON string. body: formDataJsonString, }; //Get the response body as JSON. //If the response was not OK, throw an error. let res = await fetch(url, fetchOptions); //If the response is not ok throw an error (for debugging) if (!res.ok) { let error = await res.text(); throw new Error(error); } //If the response was OK, return the response body. return res.json();}

The sample form data (formDataToJsonString) object sent as JSON;

{ "title": "Male", "username": "gisioraelvis", "usermail": "gisioraelvis@gmail.com"}

Handling JSON request body in a Node.js and Express.js API

Implementing a simple API using Node.js and Express.js, will expose an endpoint where you will be sending the request containing the form data as JSON.

Setting up the API

Node.js should be installed on your computer. To check if it is installed, run the following command:

node -v

Otherwise, install it using the following instructions.

While within the project root folder, run the following npm command to initialize the Node.js project.

npm init
(Video) POST Form Data as JSON with Fetch API in JavaScript

Fill in the relevant fields, and then proceed to the next steps.

Alternatively, you can opt to auto initialize the project with NPM default values, in that case, run npm init -y. Check this in-depth npm guide to understand how to use NPM.

npm packages used:

  • Express - To run the server and expose an endpoint that you will POST our request to. Here is a link to learn more about express.js.

  • Nodemon - This dev package ensures the server hot reloads as you make changes, so you don’t have to restart the server each time changes are made.

  • CORS or Cross-Origin Resource Sharing, allows you to send and accept requests from a different origin, bypassing the default securities applied to RESTful APIs. An awesome article on using cors in express.js.

Installing the necessary dependencies

This is all the steps to install the listed Node.js Packages:

npm install cors express

and

npm install --save-dev nodemon

The Express API/Server code.

let express = require("express");let app = express();var cors = require("cors");//cors to allow cross origin resource sharingapp.use(cors());//Middleware to parse the body of the request as JSONapp.use(express.json());//The API endpoint that the form will POST toapp.post("/formdata-as-json", (request, response) => { //Destructure the request body let resData = { serverData: request.body, }; //Console log the response data (for debugging) console.log(resData); //Send the response as JSON with status code 200 (success) response.status(200).json(resData);});//Start the server on port 5500app.listen(5500, () => console.log(`we're live 🎉`));
(Video) POST form-data file upload + JSON

Configure the following start scripts in the package.json file.

"dev": "nodemon api"

To start the server run

npm run dev

The console response on the terminal from the API:

How To Format Form Data as JSON (2)

The console response on the browser:

How To Format Form Data as JSON (3)

Here is the link to the full project on GitHub.

Conclusion

There you have it! A step by step process on how to format form data as JSON using the browser FormData API and POST it using the browser Fetch API to an API endpoint. You can utilize this newly gained knowledge and skills to develop other applications that make use of these powerful native browser APIs.

(Video) HTML form input data into JSON object | by Tech & Trainer

Happy coding!

Peer Review Contributions by: Jethro Magaji

FAQs

How To Format Form Data as JSON? ›

Using the JSON. stringify() method then format the plain form data as JSON. Specify the HTTP request method as POST and using the header field of the Fetch API specify that you are sending a JSON body request and accepting JSON responses back. Then set the request body as JSON created from the form fields.

How to convert form data to JSON file? ›

Make a plan: how can we convert form fields to JSON?
  1. Capture the form's submit event and prevent the default submission.
  2. Convert the form's child elements to JSON.
  3. Check to make sure only form field elements are added to the object.
  4. Add a safeguard to only store checkable fields if the checked attribute is set.

How to convert HTML data into JSON format? ›

HTML to JSON converter uses a DOM parser to extract data from an HTML document, create a JavaScript object from the parsed data, and convert it into JSON format using the JSON. stringify() function.

How to convert form data to JSON in Python? ›

If you have a Python object, you can convert it into a JSON string by using the json. dumps() method.

Can we send FormData as JSON? ›

Using the JSON. stringify() method then format the plain form data as JSON. Specify the HTTP request method as POST and using the header field of the Fetch API specify that you are sending a JSON body request and accepting JSON responses back. Then set the request body as JSON created from the form fields.

Why use FormData instead of JSON? ›

FormData is a bit different than JSON. It can't have nested data, it's just "key value". It can have multiple entries on one key, unlike JSON.

How to convert an object to JSON? ›

Create a new class to convert Java object to JSON object.
  1. Step 1: Create a Maven project. In the first step, we need to create a maven project using eclipse IDE. ...
  2. Step 2: Add Jackson dependency in pom.xml. ...
  3. Step 3: Create POJO to convert into JSON. ...
  4. Step 4: Create a Java class to convert the Java object into JSON.

How to store HTML data in JSON? ›

4 Things You Must Do When Putting HTML in JSON:
  1. Escape quotation marks used around HTML attributes like so <img src=\"someimage.png\" />
  2. Escape the forward slash in HTML end tags. ...
  3. This one was totally bizarre. ...
  4. Be sure to encode any quotation marks that might be included in (bad) HTML content.

How to send form data in JSON format in Postman? ›

POST request to send JSON in a form (multipart/form-data)

You need to enable this by clicking the three dots and enabling Content Type. This will allow you to create a multipart/form-data request with each part having a different content type. Notice how the part with JSON now has its own content type.

How to create JSON for table data? ›

Here are the following steps to create HTML tables using JSON data.
  1. Create a function named “convert”.
  2. Create a sample JSON data.
  3. Get the container using getElementByID(“container”) where we will append the table.
  4. Get the keys of the first object of the JSON data so that we get the headings of the table.
Feb 21, 2023

How to convert data into JSON string? ›

Stringify a JavaScript Array

Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(arr); The result will be a string following the JSON notation.

How to convert Excel file to JSON? ›

Excel to JSON using VBA code editor

Besides using all these tools, you can use the in-built feature of Excel (VBA code editor) to convert the Excel data to JSON format. Make a code for it and execute the code; it will do the mapping of Excel columns to JSON object keys and convert the data into JSON.

How to convert XML data to JSON using Python? ›

XML File to JSON String in Python

To convert an XML file into a JSON string, we can use the dumps() method defined in the json module. For this, we will first open the XML file in read mode using the open() function. Then, we will read the contents of the XML file as a string using the read() method.

How do I send form data? ›

The method attribute specifies how to send form-data (the form-data is sent to the page specified in the action attribute). The form-data can be sent as URL variables (with method="get" ) or as HTTP post transaction (with method="post" ). Notes on GET: Appends form-data into the URL in name/value pairs.

How to save form data in JavaScript? ›

JS
  1. let saveFile = () => {
  2. // Get the data from each element on the form.
  3. const name = document. getElementById("txtName");
  4. const age = document. getElementById("txtAge");
  5. const email = document. getElementById("txtEmail");
  6. const country = document. getElementById("selCountry");
  7. const msg = document.

How to post form data to JSON server? ›

Following are the steps:
  1. Create the form with its inputs and submit input/button as you would normally do.
  2. Give the form a unique Id.
  3. Add a submit event listener to the form and pass the event object with it.
  4. Build the request body in JSON format using the FormData class.
  5. Add any headers, if needed.
Sep 5, 2020

Can you store data as JSON file? ›

JSON is perfect for storing temporary data. For example, temporary data can be user-generated data, such as a submitted form on a website. JSON can also be used as a data format for any programming language to provide a high level of interoperability.

How to send data in API JSON? ›

To post JSON to a REST API endpoint, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the POST message. You must also specify the data type using the Content-Type: application/json request header.

Should I use form or JSON? ›

So ultimately, the choice rests on the complexity of the object you are sending. If the object is limited to one level deep, use straight name-value-pair; if the object is complex and involves a deeply-nested tree, use JSON.

Which data format is better than JSON? ›

YAML, Protobuf, Avro, MongoDB, and OData are the most popular alternatives and competitors to JSON.

What is a better format than JSON? ›

YAML is the most human-readable data serialization format. Many developers consider it easier to learn than JSON because it's written using natural language. YAML is a superset of JSON. It was developed around the same time to handle more kinds of data and offer a more complex but still readable syntax.

How to convert list of object to JSON format? ›

An object is an unordered collection of key/value pairs and an array is an ordered sequence of values. We can convert a list to the JSON array using the JSONArray. toJSONString() method and it is a static method of JSONArray, it will convert a list to JSON text and the result is a JSON array.

How to convert data into JSON format in JavaScript? ›

JSON.stringify() The JSON.stringify() static method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

How to convert string array into JSON object? ›

JS Array to JSON using JSON.

stringify([1, 2, 3, 4, 5]); The JSON. stringify() method converts a JavaScript object, array, or value to a JSON string. If you so choose, you can then send that JSON string to a backend server using the Fetch API or another communication library.

How to store data in JSON format in database? ›

In this post you'll learn how to:
  1. Store JSON in a database table.
  2. Query a table for rows storing particular values within a JSON document.
  3. Create indexes to find these rows efficiently.
  4. Generate JSON from relational rows and columns.
Jan 12, 2021

How to store data from HTML form? ›

HTML web storage provides two objects for storing data on the client:
  1. window.localStorage - stores data with no expiration date.
  2. window.sessionStorage - stores data for one session (data is lost when the browser tab is closed)

How to store data from HTML form to database? ›

Use Case: Create a New Order
  1. Define Queries. We will define two queries. ...
  2. Generate XML Schema. ...
  3. Create the Form. ...
  4. Link to the Database. ...
  5. Define the SQL Query. ...
  6. Generate an XML Schema. ...
  7. Create the Form. ...
  8. Link to the Database.
Sep 1, 2021

What is the difference between raw data and form data? ›

As such, we can use form-data for sending large binary or non-ASCII text to the server. The raw data type sends any plain text or JSON to the server, as the name suggests. It supports multiple content types, and Postman will send the raw data without any modifications, unlike with the other data types.

How do I pass form data in POST request? ›

To post HTML form data to the server in URL-encoded format, you need to make an HTTP POST request to the server and provide the HTML form data in the body of the POST message in key=value format. You must also specify the data type using the Content-Type: application/x-www-form-urlencoded request HTTP header.

How to post JSON data using REST template? ›

To make a POST request with the RestTemplate in JSON, you can use the postForObject() method and pass it the URL of the request, the request body, the response type, and the HttpEntity object that represents the request headers and body.

How to create JSON data in SQL? ›

SQL Server can't generate JSON with FOR JSON AUTO unless it has a schema to build the object from. The SELECT in your INSERT statement is just selecting a couple of variable values when trying to generate the JSON. In the scope of the cursor, SQL Server doesn't have any context in which to generate the JSON object(s).

How to insert JSON data into Datatable? ›

Add JSON data to DataTable
  1. on top of the XAML prepare an empty datatable with the build datatable activity and configure the needed columns.
  2. use add datarow activity for adding the data to the datatable within the for each after the Multiple Assign activity.
Feb 22, 2022

What is a table in JSON? ›

The table is the base JSON object. A table has two properties, headers and rows, which would be an array of header and row objects.

How to convert text to JSON format? ›

To change TEXT format to JSON, upload your TEXT file to proceed to the preview page. Use any available tools if you want to edit and manipulate your TEXT file. Click on the convert button and wait for the convert to complete. Download the converted JSON file afterward.

How to send string in JSON format? ›

Send JSON Data from the Client Side

Use JSON. stringify() to convert the JavaScript object into a JSON string. Send the URL-encoded JSON string to the server as part of the HTTP Request. This can be done using the HEAD, GET, or POST method by assigning the JSON string to a variable.

Can we convert SQL table to JSON? ›

MS SQL provided two options for converting data into JSON that is by using FOR JSON AUTO, and FOR JSON PATH.

Can Excel format JSON? ›

JavaScript Object Notation (JSON) is a common data format, and you can import it into Excel.

How to convert CSV data into JSON format? ›

  1. Step 1: Select your input. Enter Data.
  2. Step 2: Choose input options (optional) Input Options. ...
  3. Step 3: Choose output options (optional) Output Options. ...
  4. Step 4: Create Custom Output via Template (optional) Modify template below and Press Convert See also CSV Templates. ...
  5. Step 5: Generate output. Choose Conversion Type:

Can Excel generate JSON file? ›

Excel table data can be represented as an array of objects in the form of JSON.

What is the code for converting XML to JSON? ›

JSONObject json = XML. toJSONObject(xml); String jsonString = json. toString(4);

How to convert Python object to JSON file? ›

To dump a Python object to JSON string, you can use the json. dumps() method of the built-in json module. The json. dump() paired method (without the "s") converts the Python object to JSON string and writes it to a file.

How to add JSON language in Notepad ++? ›

Way 1. Notepad++ Format JSON via JSON Viewer
  1. Launch Notepad++ on your computer, and then navigate to the Plugins tab from the top toolbar and select Plugins Admin.
  2. In the Plugins Admin window, type JSON Viewer in the Search box and click on Next.
  3. Tick the checkbox next to JSON Viewer and click on Install.
May 31, 2022

What format is FormData? ›

A Form Data Format file is a text file that contains a list of form fields and their values. FDFMerge Pro uses the data in FDF files to assemble and fill out forms. There are two kinds of FDF files: Classic—supplies data to fill out an existing form.

What is a FormData file? ›

FormData is simply a data structure that can be used to store key-value pairs. Just like its name suggests it's designed for holding forms data i.e you can use it with JavaScript to build an object that corresponds to an HTML form.

How to pass FormData in REST API? ›

Create a form to gather data
  1. Create a web application. Mine is called multiparttest.
  2. Add an input text element by dragging it from the Component palette. This will store the "name" attribute of our REST API payload.
  3. Let us add a file picker in order to select a file from the local computer.
Sep 12, 2019

How to read data from FormData? ›

FormData: get() method

The get() method of the FormData interface returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use the getAll() method instead. Note: This method is available in Web Workers.

How to convert FormData to JavaScript object? ›

First of all, we'll create an empty object and then iterate over the FormData object we've created in the previous section: const formDataObj = {}; myFormData. forEach((value, key) => (formDataObj[key] = value));

How do I save HTML form data to text? ›

Step-by-step guide on How to put the HTML form field data in a text file or dot txt file in PHP. Create a PHP file and put the below code and save it. <! DOCTYPE html> <html> <head> <title>Store form data in .

How to convert XML data to JSON data? ›

XML to JSON Converter
  1. Select the XML to JSON action from the Tools > JSON Tools menu. ...
  2. Choose or enter the Input URL of the XML document.
  3. Choose the path of the Output file that will contain the resulting JSON document.
  4. Select how you want empty elements to be converted (default is object).

How to extract data from PDF to JSON? ›

Follow the steps below to quickly convert PDF to JSON with Nanonets:
  1. Upload a PDF file.
  2. Click to convert the file into JSON.
  3. Download the converted JSON file.

How to convert data from Excel to JSON? ›

Excel to JSON using VBA code editor

Besides using all these tools, you can use the in-built feature of Excel (VBA code editor) to convert the Excel data to JSON format. Make a code for it and execute the code; it will do the mapping of Excel columns to JSON object keys and convert the data into JSON.

Why convert XML to JSON? ›

The purpose of the XML to JSON Converter tool is to convert XML (Extensible Markup Language) code into JSON format. JSON is a lightweight data-interchange format, it's useful for exchanging data from client to server, or from server to client.

How to convert data from API to JSON? ›

To get JSON from a REST API endpoint, you must send an HTTP GET request to the REST API server and provide an Accept: application/json request header. The Accept: application/json header tells the REST API server that the API client expects to receive data in JSON format.

How to convert PDF to XML JSON? ›

Four steps for converting your PDF to XML.
  1. Use the Select tool to mark the content you want to save.
  2. Right-click the highlighted text.
  3. Choose Export Selection As.
  4. Select XML, and click Save.

How do I extract data from a PDF form? ›

In Acrobat, open the completed form file. From the All tools menu, select Prepare a form and then from the left panel that opens, select > Export data. In the Export Form Data As dialog box, select the format (FDF, XFDF, XML, or TXT) in which you want to save the form data.

What is a JSON string? ›

JSON is purely a string with a specified data format — it contains only properties, no methods. JSON requires double quotes to be used around strings and property names. Single quotes are not valid other than surrounding the entire JSON string.

Videos

1. Create JSON Data | How to create specific json data format to send api
(Seema Holiday Developer)
2. Append json in file using php form
(Wordpress with Kapil)
3. How to store form data in a json file using php | PHP & JSON Tutorial
(Digital Fox)
4. how to convert your data into Json format in python =
(Soumil Shah)
5. Customize SharePoint List Forms using JSON Formatting (1)
(Reza Dorrani)
6. How to save data to JSON file
(Chascript)

References

Top Articles
Latest Posts
Article information

Author: Edmund Hettinger DC

Last Updated: 08/22/2023

Views: 5838

Rating: 4.8 / 5 (58 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Edmund Hettinger DC

Birthday: 1994-08-17

Address: 2033 Gerhold Pine, Port Jocelyn, VA 12101-5654

Phone: +8524399971620

Job: Central Manufacturing Supervisor

Hobby: Jogging, Metalworking, Tai chi, Shopping, Puzzles, Rock climbing, Crocheting

Introduction: My name is Edmund Hettinger DC, I am a adventurous, colorful, gifted, determined, precious, open, colorful person who loves writing and wants to share my knowledge and understanding with you.