I need to create dynamically hidden elements with name - value to store a JSON object.
For this input:
json_structure = {
'var_1':'value_1',
'var_2': {
'var_2_1':'value_2_1',
'var_2_2':'value_2_2'
},
'var_3': 'value_3'
};
should have
<input type="hidden" name="var_1" value="value_1" />
<input type="hidden" name="var_2[var_2_1]" value="value_2_1" />
<input type="hidden" name="var_2[var_2_2]" value="value_2_2" />
<input type="hidden" name="var_3" value="value_3" />
EDIT1 Here is my example, but works only for a one level object. For multiple levels need to make a recursive function to build the entire structure.
for(var key in json_structure ) {
if(json_structure .hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", json_structure [key]);
form.appendChild(hiddenField);
}
}
Is there a way to do this in a JavaScript or jQuery function which makes this easier?
Thank you in advance!