【问题标题】:JSON Stringify a sublistJSON Stringify 子列表
【发布时间】:2012-07-24 00:42:17
【问题描述】:

这可能是一个菜鸟问题,但如果我想制作一个 JSON 项目列表(在 nodejs 应用程序中),我可以执行以下操作:

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'} }

【问题讨论】:

  • 谢谢您,您的所有回答都非常有帮助,哈哈

标签: javascript json node.js


【解决方案1】:

{} 是对象字面量语法,propertyName: propertyValue 定义了一个属性。继续嵌套它们。

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

【讨论】:

    【解决方案2】:

    使用 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));​
    

    【讨论】:

      【解决方案3】:

      这样:

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

      【讨论】:

        【解决方案4】:

        你会这样做:

        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'
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2013-01-21
          • 2018-12-15
          • 1970-01-01
          • 2017-11-18
          • 2021-07-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-02-11
          相关资源
          最近更新 更多