Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

129
Vistas
Automatically encode form input to JSON with native datatype

I'm aware (from this) I can explicitly convert a value to an integer before passing it to JSON.stringify. But this approach is not useful when you want to serialize a form data. I have a generic code:

let myform='#my_form_id`;
$(myform).submit(function(event) {
    event.preventDefault();
    const formData = new FormData($(myform)[0]);
    const json = JSON.stringify(Object.fromEntries(formData));
    ws.send(json); // send over websocket
});

And I really don't want to manually convert each field to the appropriate type before serialization. It's against all the rules of a "well-written" code.

So, how can I serialize the form fields in JSON keeping their native data types?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can map over the inputs and use a switch case to choose what data and type is returned.

$('form').on('submit', function(e) {
  e.preventDefault();
  
  let json = JSON.stringify($(this).find('input').get().map(function(input){
    switch (input.type) {
      case 'checkbox':
      case 'radio': return input.checked; break;
      case 'number':
      case 'range': return +(input.value || 0); break;
      default: return input.value || ''
    }
  }));
  
  $('.json').html(json);
});
<form>
  <div>
    <input>
    <input type="number">
    <input type="checkbox">
    <input type="radio">
    <input type="color">
    <input type="date">
    <input type="range">
  </div>
  <div>
    <input>
    <input type="number">
    <input type="checkbox">
    <input type="radio">
    <input type="color">
    <input type="date">
    <input type="range">
  </div>
  <button action="submit">SERIALIZE</button>
</form>
<p class="json"></p>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda