我有一个具有以下结构的json文件:
{
"Branch 1": {
"name": "Branch 1 Name",
"image": "branch1.jpg",
"categories": {
"category 1": {
"name": "Category 1 Name",
"image": "Category1.jpg",
"products":{
"product1":{
"id": "245748",
"name": "product 4",
"description": "description 1"
},
"product2":{
"id": "245738",
"name": "product 5",
"description": "description 2"
},
"product3":{
"id": "123738",
"name": "product 6",
"description": "description 3"
}
}
},
"category 2": {
"name": "Category 2 Name",
"image": "Category2.jpg",
"products":{
"product1":{
"id": "444738",
"name": "product 4",
"description": "description 1"
},
"product2":{
"id": "554738",
"name": "product 5",
"description": "description 2"
},
"product3":{
"id": "432738",
"name": "product 6",
"description": "description 3"
}
}
}
}
},
"Branch 2": {
"name": "Branch 2 Name",
"image": "branch2.jpg",
"categories": {
"category 1": {
"name": "Category 1 Name",
"image": "Category1.jpg",
"subCategories": {
"subCategory 1": {
"name": "subCategory 1 Name",
"image": "subCategory1.jpg",
"products":{
"product1":{
"id": "654433",
"name": "product 4",
"description": "description 1"
},
"product2":{
"id": "432123",
"name": "product 5",
"description": "description 2"
},
"product3":{
"id": "776534",
"name": "product 6",
"description": "description 3"
}
}
},
"subCategory 2": {
"name": "subCategory 2 Name",
"image": "subCategory2.jpg",
"products":{
"product1":{
"id": "446534",
"name": "product 4",
"description": "description 1"
},
"product2":{
"id": "116534",
"name": "product 5",
"description": "description 2"
},
"product3":{
"id": "772234",
"name": "product 6",
"description": "description 3"
}
}
}
}
},
"category 2": {
"name": "Category 2 Name",
"image": "Category2.jpg",
"subCategories": {
"subCategory 1": {
"name": "subCategory 1 Name",
"image": "subCategory1.jpg",
"products":{
"product1":{
"id": "321234",
"name": "product 4",
"description": "description 1"
},
"product2":{
"id": "433534",
"name": "product 5",
"description": "description 2"
},
"product3":{
"id": "123434",
"name": "product 6",
"description": "description 3"
}
}
},
"subCategory 2": {
"name": "subCategory 2 Name",
"image": "subCategory2.jpg",
"products":{
"product1":{
"id": "887663",
"name": "product 4",
"description": "description 1"
},
"product2":{
"id": "879767",
"name": "product 5",
"description": "description 2"
},
"product3":{
"id": "987678",
"name": "product 6",
"description": "description 3"
}
}
}
}
}
}
}
}
如何输出此json文件的特定图层。我有一个页面,我只需要分支,另一个页面,我只需要分支的分类。然后更深入一页,我只需要一个类别或分支的子类别。在最深的页面,我只需要一个类别的产品。
是否有一种简单的方法可以解析这个json文件并访问它""层"根据需要?
答案 0 :(得分:0)
// parse json to object
var obj = JSON.parse(yourJSON);
// deep copy the part of the object that you need
var categories = jQuery.extend({}, obj.categories);
// make a json out of it, if that's what you need
var categoriesJSON = JSON.stringify(categories);
最后一步是如果你真的需要它作为JSON,但我想情况并非如此,你可以在你的页面上使用categories
对象。