jqueryhtmljsondiagram

HTML Attributes to JSON


I've been developing a diagramming tool/editor. The data that I need to store is in the HTML attributes. Is there a way to get this data?

This is the screenshot of what I am telling

Also, I need the diagram to be converted to JSON

function createJSON(){
    var data = new Object();
    $("input[class = process]").each(function() {
        data[$(this).attr("name")] = $(this).val();
        jsonString = JSON.stringify(data);
    });

This works but I need the html attributes to be converted into json too.


Solution

  • Iterate over the attributes property:

    var data = {};
    
    $("input[class=process]").each(function () {
        var name = $(this).attr("name");
        data[name] = {};
        $.each(this.attributes, function (i, attr) {
            if (attr.specified) {
                data[name][attr.name] = attr.value;
            }
        });
    });
    
    console.log(JSON.stringify(data));
    

    Then to restore it, you can do something like this:

    $("input[class=process]").each(function () {
        var $this = $(this),
            name  = $this.attr("name");
        if (typeof data[name] === "undefined") {
            return;
        }
        $.each(data[name], function (name, value) {
            $this.attr(name, value);
        });
    });