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

时间:2013-12-14 03:14:27

标签: javascript jquery json

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

喜欢:

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对象可以嵌套。对于这个noob问题再次抱歉。

好吧,我写的是这样的:

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不匹配... Haven救了我:(

2 个答案:

答案 0 :(得分:1)

我编写了一些应该处理你问题的东西。如果我理解你的话,这正是你所需要的。

我使用递归和访问者模式解决了这个问题。奇迹般有效。 我没有为所有可能的类型测试它,但是在需要时可以轻松插入缺少的类型。 数组目前崩溃 - 如果它们也出现,你将需要捕获它。

一些解释:

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元素那样被完全对待)

答案 1 :(得分:1)

您是否只是在寻找jQuery的.attr()?您可以创建一个元素,添加一些属性和文本,然后将其附加到正文:

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