简体   繁体   中英

Build JSON-object from form

I have a form with the following format (only parts of the form)

<input type="text" name="Journal[data][serviceaddress][company]" value="{{company}}"/>
<input type="text" name="Journal[data][serviceaddress][address]" value="{{address}}"/>
<input type="text" name="Journal[data][serviceaddress][zip]" value="{{zip}}"/>
<textarea name="Journal[data][serviceaddress][notes]">{{notes}}</textarea>
<input type="text" name="Journal[rows][1][title]"/>
<input type="text" name="Journal[rows][1][body]"/>
<input type="text" name="Journal[rows][2][title]"/>
<input type="text" name="Journal[rows][2][body]"/>

I'd like to convert this to the following JSON-object

{
    data:{
        serviceaddress:{
            company: "companyvalue",
            address: "addressvalue",
            zip: "zipvalue",
            notes: "notesvalue"
        }
    },
    rows:{
        1:{
            title: "row1title",
            body: "row1body"
        },
        2:{
            title: "row2title",
            body: "row2body"
        }
    }
}

Which would be the best way to do this? I thought that i must be someone who did this already, but all i found when searching was people wanting the input name as the key and not nested JSON-data...

Since i couldn't find anything existing that i found were a satisfying solution, i created my own and here it is

function getData(){
            var data = {};
            $('.data input,.data textarea').each(function(){
                var val = $(this).val();
                var namestr = $(this).attr('name').substr(8);
                namestr = namestr.substring(0,namestr.length-1);
                var namearray = namestr.split('][');

                var currentlevel = data;
                if (namearray[0] == 'data'){
                    namearray = namearray.splice(1,namearray.length);
                    for (var i=0;i < namearray.length;i++){
                        if (currentlevel[namearray[i]] == undefined && i != namearray.length-1){
                            currentlevel[namearray[i]] = {};
                        }
                        else if (namearray.length-1 == i){
                            currentlevel[namearray[i]] = val;
                            break;
                        } //In the end, put a value
                        currentlevel = currentlevel[namearray[i]]
                    }   
                }
            });
            return data;
        }

As you can see, this only looks at input/textarea-tags where the first "array" parameter in the name is "data", that is it will only parse fields where name is of the format "Myform[data][value1]". This can easily be modified to your own needs.

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