2012-07-24 67 views
0

这可能是一个noob问题,但如果我想使项目的JSON列表(在的NodeJS应用程序),我可以做到以下几点:JSON字符串化的子列表

var myVar = { 
    'title' : 'My Title', 
    'author' : 'A Great Author' 
}; 

console.log(JSON.stringify(myVar)); 

OUTPUT: { 'title' : 'My Title', 'author' : 'A Great Author' } 

,一切的伟大工程,但我如何制作如下的子列表?

OUTPUT: { book {'title' : 'My Title', 'author' : 'A Great Author'} } 
+0

谢谢你,所有的答案都非常有帮助的笑 – Scott 2012-07-24 01:07:22

回答

2

{}是对象文字语法,propertyName: propertyValue定义的属性。继续前进并嵌套它们。

var myVar = { 
    book: { 
     'title' : 'My Title', 
     'author' : 'A Great Author' 
    } 
}; 
0

作为这样:

var myVar = { 
    'book': { 
     'title' : 'My Title', 
     'author' : 'A Great Author' 
    } 
}; 
0

你会做这样的事情:

myVar = { 
    book: { 
     'title' : 'My Title', 
     'author' : 'A Great Author' 
    } 
} 

console.log(JSON.stringify(myVar)); // OUTPUT: { book {'title' : 'My Title', 'author' : 'A Great Author'} } 

如果你想在子列表中的多个项目,你会改成这样:

myVar = { 
    book1: { 
     'title' : 'My Title', 
     'author' : 'A Great Author' 
    }, 
    book2: { 
     'title' : 'My Title', 
     'author' : 'A Great Author' 
    } 
} 
1

若要做到这一点JavaScript:

var mVar = { 
    'title' : 'My Title', 
    'author' : 'A Great Author' 
}; 

var myVar = {}; 

myVar.book = mVar; 

console.log(JSON.stringify(myVar));​ 

请参阅:http://jsfiddle.net/JvFQJ/

要使用对象的文字符号做到这一点:

var myVar = { 
    'book': { 
     'title' : 'My Title', 
     'author' : 'A Great Author' 
    } 
}; 

console.log(JSON.stringify(myVar));​