marioizquierdo / jquery.serializeJSON

Serialize an HTML Form to a JavaScript Object, supporting nested attributes and arrays.
MIT License
1.71k stars 434 forks source link

Deserialize JSON into form #71

Closed koder217 closed 7 years ago

koder217 commented 7 years ago

Hi,

Your plugin is very useful. However, it's only helpful in getting json from Form. Is there a way I can deserialize json and load it into the form i.e, setting the form with a JSON object ?

That would be extremely useful.

marioizquierdo commented 7 years ago

Sorry, this plugin doesn't deserialize.

The reason is that doing all the inverse operations, supporting all the options is quite difficult, it would add too much complexity to the plugin for "little gain".

In the other hand, it is very easy to do manually with plain jQuery, just assign the values manually, for example:

// Fill form where input names follow the serializeJSON format.
var fillForm($form, data) {
  $form.find('[name="user[firstName]]"').val(data["user"]["firstName"]);
  $form.find('[name="user[lastName]]"').val(data["user"]["lastName"]);
  $form.find('[name="isCool"]').prop("checked", data["isCool"]); // checkbox with a bool value
}

Then you can deserialize your data back to your form:

fillForm($("#user-form"), {
  user: {
    firstName: "John",
    lastName: "Doe"
  },
  isCool: true
});

There are some other recommendations in StackOverflow and I also found a little plugin that may work for you: jquery.forms.populator.