一个javascript类,它接受JSON对象并将其转换为属性属性

A javascript class that takes a JSON object and converts it into an attribute property

本文关键字:属性 转换 对象 JSON javascript 一个      更新时间:2023-09-26

我尝试用javascript将JSON对象转换为属性字符串。

类似:

json = {a:"1", b:"2"};

输出将是html元素,如

"< div a='1', b='2'>< /div>"

我试过了,

var json = {a:"1",    b:{c:"2", d:"3"}};
function myFunction(obj, json) {
    for (var i in json) {
        obj[i] = json[i];
    }
}

据我所知,obj已经创建,但我没有做出可以在html中使用的正确输出,因为json对象可以嵌套。再次为这个问题道歉。

好吧,我写这样的东西:

var o = {a:"1",    b:{c:"2", d:"3"}}    
function objToString (obj) {
    var str = '<div ';
    for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
            str += p + '=' + '"'+obj[p]+'"' + ',';
        }
    }
    str= str.replace(/,$/ , '>');
    return str;
}
objToString (o);

但是上面的代码不适用于嵌套对象。所以,我尝试了这种方式:

var o = {
    a: "1",
    b: {
        c: "2",
        d: "3"
    }
}
console.log(o);
var tx = new String();
tx = '<div ' + JSON.stringify(o) + '>';
console.log(tx);
tx.replace(/:/gi, '=');
tx = tx.replace(/}/, '');
tx = tx.replace(/{/, '');
console.log(tx);

但这一次的输出与正确的html不匹配。。。避风港救我:(

我编写了一些程序来处理您的问题。如果我理解得对,这正是你所需要的。

我使用递归和访问者模式解决了这个问题。工作起来很有魅力。我没有对所有可能的类型进行测试,但在需要时可以很容易地插入缺失的类型。数组当前确实崩溃了——如果它们也出现了,你需要抓住它。

一些解释:

1) 我测试了这些值的类型。

2) 我初始化了一个数组,用来存储我能找到的值。

3) 我写了一个递归方法,测试对象属性是否为对象

4) 如果属性是一个对象,它将在相同的方法中递归使用。

5) 如果该属性不是对象,则其数据将添加到先前初始化的数组中。

6) 执行递归方法后,我调试数组并创建一个示例输出。

// the object to use:   
var o = {a:1,    b:{c:"2", d:"3"}}  
// some type testing:
//alert(typeof(o.a)); // string
//alert(typeof(o.b)); // object

// implement a recursive method that reads all
// the needed stuff  into a better-to-handle array.
function readAttributesRecursive(obj, arr) {
    for(prop in obj) {
        // get the value of the current property.
        var propertyValue = obj[prop];
        // get the value's type
        var propertyValueType = typeof(propertyValue);

        // if it is no object, it is string, int or boolean.
        if(propertyValueType !== 'object') {
            arr.push({
                property : prop,
                value : propertyValue,
                type : propertyValueType // just for debugging purposes
            });
        } 
        // otherwise it is a object or array. (I didn't test arrays!)
        // these types are iterated too.
        else {
            // red the object and pass the array which shall 
            // be filled with values. 
            readAttributesRecursive(propertyValue, arr);
        }
    }
} // END readAttributesRecursive(obj, arr)

// ok, lets get the values:
var result = new Array();
readAttributesRecursive(o, result)
console.debug(result);
//  the result looks like this:
//  [
//      { property : "a", type : "number", value: "1" }
//      { property : "c", type : "string", value: "2" }
//      { property : "d", type : "string", value: "3" }
//  ]

// And now do the <div>-stuff:
var div = '<div';
for(i = 0; i < result.length; i++) {
    var data = result[i];
    div += ' ' + data.property + '="' + data.value + '"';
}
div += ">Some text</div>";
console.debug(div);

注:请永远不要创建这样的HTML元素(使用字符串)!使用document.createElement()并使用创建的DOM元素。使用字符串可能会导致奇怪的行为、错误和可读性较差的代码。。。(字符串在插入DOM后并没有像DOM元素一样被精确地处理)

您只是在寻找jQuery的.attr()吗?您可以创建一个元素,添加一些属性和文本,并将其附加到正文中,如下所示:

$('<div/>')
  .attr({
    "class":"some-class",
    "id":"some-id",
    "data-fancy": "fancy pants"
  })
  .text('Hello World')
  .appendTo('body');