Javascript formdata to json

How to convert formdata (html5 object) to json in Javascript?

Converting a FormData object to JSON in JavaScript is a common task when working with forms and APIs. The FormData object provides a convenient way to collect and send form data, but it can be tricky to convert it to a JSON object for use in other parts of your application. In this article, we will look at different methods for converting a FormData object to JSON.

Method 1: Using the entries() method

Here is an example code snippet that shows how to convert a FormData object to JSON using the entries() method:

const formData = new FormData(document.querySelector('form')); const json = JSON.stringify(Object.fromEntries(formData.entries())); console.log(json);

In the above code, we first create a new FormData object from a form element using the FormData() constructor.

Then, we use the entries() method of the FormData object to get an iterator of key-value pairs. We pass this iterator to the Object.fromEntries() method to create an object from the key-value pairs.

Finally, we use the JSON.stringify() method to convert the object to a JSON string.

Here’s another example that shows how to convert a FormData object to a nested JSON object:

const formData = new FormData(document.querySelector('form')); const json = JSON.stringify( Array.from(formData.entries()).reduce((obj, [key, value]) =>  obj[key] = obj[key] || []; obj[key].push(value); return obj; >, >) ); console.log(json);

In this example, we first create a new FormData object from a form element using the FormData() constructor.

Then, we use the entries() method of the FormData object to get an iterator of key-value pairs. We convert this iterator to an array using the Array.from() method.

Next, we use the reduce() method to create a nested object from the key-value pairs. For each key-value pair, we check if the key already exists in the object. If it does not exist, we create a new array for the key. We then push the value to the array.

Finally, we use the JSON.stringify() method to convert the object to a JSON string.

Method 2: Using Object.fromEntries()

To convert FormData to JSON using Object.fromEntries(), you can follow these steps:

  1. Get all the entries from the FormData object using the entries() method.
  2. Convert the entries to an array using the spread operator.
  3. Map the array to an object using Object.fromEntries().
const formData = new FormData(document.querySelector('form')); // Step 1 const entries = formData.entries(); // Step 2 const data = [. entries]; // Step 3 const json = Object.fromEntries(data); console.log(json);

This will output a JSON object containing all the key-value pairs from the FormData object.

Here’s another example that uses a button click event to convert FormData to JSON:

form> label for="name">Name:label> input type="text" id="name" name="name"> br> label for="email">Email:label> input type="email" id="email" name="email"> br> button type="button" id="submit">Submitbutton> form> script> const submitBtn = document.getElementById('submit'); submitBtn.addEventListener('click', () =>  const formData = new FormData(document.querySelector('form')); const entries = formData.entries(); const data = [. entries]; const json = Object.fromEntries(data); console.log(json); >); script>

This code will convert the form data to JSON when the submit button is clicked and log it to the console.

In summary, to convert FormData to JSON using Object.fromEntries(), you need to get the entries from the FormData object, convert them to an array, and then use Object.fromEntries() to map the array to an object.

Method 3: Using a for. of loop

To convert a FormData object to JSON using a for. of loop, you can follow these steps:

let formData = new FormData(); let convertedData = >;
for (let [key, value] of formData)  // code goes here >
for (let [key, value] of formData)  convertedData[key] = value; >
let jsonData = JSON.stringify(convertedData);

Here’s the full code example:

let formData = new FormData(); formData.append('name', 'John'); formData.append('email', 'john@example.com'); let convertedData = >; for (let [key, value] of formData)  convertedData[key] = value; > let jsonData = JSON.stringify(convertedData); console.log(jsonData);
"name":"John","email":"john@example.com">

Источник

Converting FormData to JSON in JavaScript

FormData is a useful interface for collecting data from a form. But it can be tricky to convert to JSON.

The FormData interface is a super convenient way to collect data from a element. This makes the process of submitting form requests asynchronously a total walk in the park.

It works really great out of the box if you’re able to send your request using the multipart/form-data encoding type. But what often happens is the service that is receiving that data isn’t setup to work with that encoding. That’s because it’s not as easy to work with. It’s often a cleaner approach to be able to accept JSON on the server side and use that to (do whatever) with the form data.

Sending FormData Directly

Let’s say we have a super simple form, with one field to collect a name:

form onsubmit="submitForm(event)"> 
label>Namelabel>
br />
input type="text" name="name" required />
br />br />
input type="submit" value="Submit" />
form>

Don’t actually use onsubmit to call a global function in production. Here are a couple alternate patterns worth considering.

We could then submit the data through some JavaScript function:

function submitForm(event)  
// Prevent the form from submitting.
event.preventDefault();
// Set url for submission and collect data.
const url = "https://example.com/. ";
const formData = new FormData(event.target);
// Submit the data.
const request = new XMLHttpRequest();
request.open("POST", url);
request.send(formData);
>

That works great if your server (or serverless function) can process the data directly.

Converting FormData to JSON

Now here’s the weird thing. If you inspect formData from the function above, it looks like there’s nothing there.

function submitForm(event)  
// Prevent the form from submitting.
event.preventDefault();
// Set url for submission and collect data.
const url = "https://example.com/. ";
const formData = new FormData(event.target);
// Log the data.
console.log(formData);
>

This will result in a log to the console like this:

Coooool. That’s not helpful.

Instead, we actually have to iterate over the field individually and build an object manually.

function submitForm(event)  
// Prevent the form from submitting.
event.preventDefault();
// Set url for submission and collect data.
const url = "https://example.com/. ";
const formData = new FormData(event.target);
// Build the data object.
const data = >;
formData.forEach((value, key) => (data[key] = value));
// Log the data.
console.log(data);
>

Now fill in the field with something like «My Name» and submit the form. You’ll see the object logged to the console:

Handling All Cases

That will solve for many cases, but not all. This StackOverflow answer offers a solution for handling multi-select lists. Check out the demo.

Источник

Как преобразовать объект FormData в JSON

JSON JavaScript Object Notation, это текстовый формат представления данных в нотации объекта JavaScript . Предназначен JSON, также как и некоторые другие форматы такие как XML и YAML , для обмена данными.

Получаем объект FormData и преобразовываем в JSON :

document.querySelector("button[type=submit]").addEventListener("click", (event) => < // отмена действия кнопки event.preventDefault(); // находим форму по name="student" let form = document.forms["student"]; // создаем пустой объект var object = <>; // получаем через метод FormData нашу форму let data = new FormData(form); // перебираем поля формы data.forEach(function (value, key) < // создаем классический объект objectJavascript formdata to json = value; >); // сериализуем объект в Json var json = JSON.stringify(object); // выводим результат в консоль console.log(json); >);

Получение данных на сервере

К примеру вам нужно отправить json сериализованную строку, передавать это нужно через POST запрос, длина GET запроса ограничена 4мя килобайтами. Если попытаться получить GET запрос через суперглобальную переменную $_POST , нечего не выйдет!

Данные, которые могут быть обработаны через $_POST :

  • application/x-www-form-urlencoded тип application/x-www-form-urlencoded для простых форм application/x-www-form-urlencoded
  • multipart/form-data-encoded в основном multipart/form-data-encoded для загрузки файлов

Перечисленное выше, это единственные типы контента которые должны поддерживаться браузерами. Поэтому сервер и PHP традиционно не ожидают получения какого-либо другого типа контента.

Если много работаете с Ajax, может понадобиться обмен более сложными данными с типами строка , int , bool и структурами массивы , объекты , поэтому в большинстве случаев JSON является лучшим выбором:

Содержимое будет иметь заголовок application/json он не пречислен в поддерживаемых по умолчанию, так что переменная $_POST из PHP не знает, как с этим справиться.

Получить запрос можно в сыром виде с помощью нераспределенного запроса PHP:

file_get_contents('php://input');

Источник

Читайте также:  Основная структура html кода
Оцените статью