我目前正致力于一项必须对JS和JSON对象做很多工作的任务。我有我的Javascript对象设置,但我只是好奇如何将两个对象存储在一个' master'对象以及如何将该数据输出到页面。
这是我的代码:
var javabook = {
"book": {
"isbn" : "0-596-00016-2",
"title" : "Java and XML",
"price" : "39.95",
"publisher" : "O'Reilly & Associates",
"copyright": "2000",
"authors": {
"author": {
"fname": "Brett",
"lname": "McLaughlin",
"price": "22.00"
}
}
}
};
var vb6book = {
"book": {
"isbn" : "1-861003-32-3",
"title" : "Professional Visual Basic 6 XML",
"price" : "49.99",
"publisher" : "Wrox Press",
"copyright": "2000",
"authors": [{
"fname": "James",
"lname": "Britt",
"price": ""
}, {
"fname": "Tuen",
"lname": "Duynstee",
"price": ""
}]
}
};
var myJSON = JSON.stringify(javabook);
var myJSON2 = JSON.stringify(vb6book);
var textbooks = [javabook, vb6book];
document.getElementById("demo").innerHTML = myJSON;
document.getElementById("demo2").innerHTML = myJSON2;
所以我要做的就是存储你看到名为' javabook'的两个对象。和vr6book合并为一个主要对象,然后将它们显示到页面中。总的来说,我需要帮助将这两个JS对象分成主对象,然后能够单独访问它们并将它们输出到带有JSON stringify的页面,然后让它们出现在页面上。那么这个JS对象将如何转换为基本的JSON对象?我的意思是除了我对JS的问题之外,我的代码在标准JSON格式中看起来如何,因为我想了解更多关于它的信息?感谢任何帮助,谢谢!
答案 0 :(得分:2)
var javabook = {
"book": {
"isbn" : "0-596-00016-2",
"title" : "Java and XML",
"price" : "39.95",
"publisher" : "O'Reilly & Associates",
"copyright": "2000",
"authors": {
"author": {
"fname": "Brett",
"lname": "McLaughlin",
"price": "22.00"
}
}
}
};
var vb6book = {
"book": {
"isbn" : "1-861003-32-3",
"title" : "Professional Visual Basic 6 XML",
"price" : "49.99",
"publisher" : "Wrox Press",
"copyright": "2000",
"authors": [{
"fname": "James",
"lname": "Britt",
"price": ""
}, {
"fname": "Tuen",
"lname": "Duynstee",
"price": ""
}]
}
};
var masterobject = {
javabook: javabook,
vb6book: vb6book
};
然后,您可以使用以下命令访问该对象:
var book1 = JSON.stringify(masterobject.javabook);
var book2 = JSON.stringify(masterobject.vb6book);
document.getElementById("demo").innerHTML = book1;
document.getElementById("demo2").innerHTML = book2;
答案 1 :(得分:1)
{{1}}