2012-07-24 89 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));​