Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!