简体   繁体   中英

create json array and append objects in it from form

At this moment I'm trying to create a json like this.

[
{"name": "set registry key right",
"win_acl": {
  "path": "HKCU:\\Bovine\\Key",
  "user": "BUILTIN\\Users",
  "rights": "EnumerateSubKeys",
  "type": "allow",
  "state": "present",
  "inherit": "ContainerInherit, ObjectInherit",
  "propagation": "None"
}
},
{
"name": "Remove FullControl AccessRule for IIS_IUSRS",
"win_acl": {
  "path": "C:\\inetpub\\wwwroot\\MySite",
  "user": "IIS_IUSRS",
  "rights": "FullControl",
  "type": "allow",
  "state": "absent",
  "inherit": "ContainerInherit, ObjectInherit",
  "propagation": "None"
}
}
]

I want to create it dynamically trough javascript.

This is what I have now:

    function GenerateYaml(btn) {
    $('#generatedYamlTextField').removeAttr("hidden");

    var id = btn.replace("generateBtn", "");
    var moduleName = $("#formpanel" + id).attr("data-title-caption");

    //Looping trough panels
    $("#formpanel" + id).each(function () {

        var json = "[\n{\n\"name\":\"" + "module beschrijving" + "\",\n";
        json += "\"" + moduleName + "\": {\n";
        //Looping through labels in the panel to create the object
        $('label').each(function (index, value) {
                            var is_last_item = (index == ($('label').length - 1));

            if (!is_last_item) {
                json += "\"" + value.innerText + "\":"+"\"textboxvalue\",\n";
            } else {

                json += "\"" + value.innerText + "\":"+"\"textboxvalue\"\n";

            }

        });

        json += "}\n},]\n";
        $("#yamltextfield").append(json);

    });   
}

This is what I get from above code in my textarea:

[
{
"name":"module beschrijving",
"win_acl_inheritance_module": {
"path":"textboxvalue",
"reorganize":"textboxvalue",
"state":"textboxvalue"
}
},]

My problem is that I have multiple panels and I want to add them in the same array so that I get it like the json I showed in the first place.

I hope you guys could help me out. Thanks in advance.

Greetings, Mouaad

Don't form the json string manually. Just compose your objects, put them in an array, say arr and you can get the json string by:

JSON.stringify(arr);

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