简体   繁体   中英

Convert json object structure to html input elements

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 work only for a one level object. For multiple level need to make a recursive function to build the entyre 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 wich make this easyear?

Thank you in advance!

You can use some recursive approach to generate the input code where use Object.keys and Array#forEach method for iterating over the object properties.

 var json_structure = { 'var_1': 'value_1', 'var_2': { 'var_2_1': 'value_2_1', 'var_2_2': 'value_2_2' }, 'var_3': 'value_3' }; // function forr generating input function genInput(obj, res, prefix) { // get all the object keys and iterate Object.keys(obj).forEach(function(k) { // generate the name with prefix var name = prefix ? prefix + '[' + k + ']' : k; // check property value is object // in case its object call the function recursively if (typeof obj[k] == 'object') // skip null by checking value is truthy obj[k] && genInput(obj[k], res, name); // else generate the input and push into the output array else res.push('<input type="hidden" name="' + name + '" value="' + obj[k] + '"/>') }) // finally return the array generated return res; } console.log( genInput(json_structure, []) ) 


For generating DOM element and updating either you can use jQuery with the above code or with pure java do something like this.

 var json_structure = { 'var_1': 'value_1', 'var_2': { 'var_2_1': 'value_2_1', 'var_2_2': 'value_2_2' }, 'var_3': 'value_3' }; function genInput(obj, form, prefix) { Object.keys(obj).forEach(function(k) { var name = prefix ? prefix + '[' + k + ']' : k; if (typeof obj[k] == 'object') { obj[k] && genInput(obj[k], form, name); } else { var hiddenField = document.createElement("input"); hiddenField.setAttribute("type", "hidden"); hiddenField.setAttribute("name", name); hiddenField.setAttribute("value", obj[k]); form.appendChild(hiddenField); } }) } genInput(json_structure, document.getElementsByTagName('form')[0]) 
 <form></form> 

With jQuery :

 var json_structure = { 'var_1': 'value_1', 'var_2': { 'var_2_1': 'value_2_1', 'var_2_2': 'value_2_2' }, 'var_3': 'value_3' }; // function forr generating input function genInput(obj, res, prefix) { Object.keys(obj).forEach(function(k) { var name = prefix ? prefix + '[' + k + ']' : k; if (typeof obj[k] == 'object') obj[k] && genInput(obj[k], res, name); else res.push('<input type="hidden" name="' + name + '" value="' + obj[k] + '"/>') }) return res; } // append the array of html string $('form').append(genInput(json_structure, [])) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form></form> 

You don't actually need jQuery in this case.

Here's a slightly different version.

 var json_structure = { 'var_1':'value_1', 'var_2': { 'var_2_1':'value_2_1', 'var_2_2':'value_2_2' }, 'var_3': 'value_3' }; function createHiddenInput(name, value) { var hiddenInput = document.createElement("input"); hiddenInput.setAttribute("type", "hidden"); hiddenInput.setAttribute("name", name); hiddenInput.setAttribute("value", value); document.body.appendChild(hiddenInput); console.log(hiddenInput); } function generateInputs(structure, prepend) { for (var propertyKey in structure) { if (structure.hasOwnProperty(propertyKey)) { var property = json_structure[propertyKey] if (typeof property === 'object') { generateInputs(property, propertyKey) } else { var name = prepend ? prepend + '[' + propertyKey + ']' : property; createHiddenInput(name, propertyKey) } } } } generateInputs(json_structure) 
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> </head> <body> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM