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가 생성되었지만 json 객체가 중첩 될 수 있기 때문에 html에서 사용할 수있는 적절한 출력을 만들지 못했습니다. 이 멍청한 질문에 대해 다시 한 번 죄송합니다.
글쎄, 나는 다음과 같이 씁니다.
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 save me :(
나는 당신의 문제를 다루어야 할 것을 프로그램했습니다. 내가 당신이 옳다는 것을 이해했다면 이것이 바로 당신에게 필요한 것입니다.
재귀와 방문자 패턴을 사용하여이 문제를 해결했습니다. 매력처럼 작동합니다. 가능한 모든 유형에 대해 테스트하지는 않았지만 누락 된 유형은 필요할 때 쉽게 삽입 할 수 있습니다. 배열이 현재 충돌합니다.이 경우에도이를 포착해야합니다.
몇 가지 설명 :
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 요소처럼 정확하게 처리되지 않습니다.)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다