【问题标题】:Creating nested JSON object [closed]创建嵌套的 JSON 对象 [关闭]
【发布时间】:2014-09-17 13:10:21
【问题描述】:

我有一个现有的 JSON 模型,例如

    var oData = {
{section: "section1",description: "item1 description",checked: true }
{section: "section1",description: "item2 description",checked: true }
{section: "section2",description: "item1 description",checked: true }
{section: "section2",description: "item2 description",checked: true }
{section: "section3",description: "item1 description",checked: true }
}

我正在尝试从现有的 json 模型创建这样的结构

  var oData = {
    {section: "section1" 
             {description: "item1 description",checked: true } ,
             {description: "item2 description",checked: true }
    }
    {section: "section2" 
             {description: "item1 description",checked: true } ,
             {description: "item2 description",checked: true }
    }
    {section: "section3" 
             {description: "item1 description",checked: true } }
    }

我正在寻找完成此任务的最佳方法

【问题讨论】:

  • 这些代码 sn-ps 都不是 JSON。它们甚至不是有效的 JavaScript。
  • 您提供的预期结果不正确。您正在混合类型“section1” {desc ... - 这很糟糕。所以你的请求无效。
  • 那些是 javascript 对象字面量(格式错误的字面量)而不是 JSON。
  • daksh 列出的结构工作如何重构现有模型?

标签: javascript arrays json


【解决方案1】:

在不知道你想使用它的方式的情况下决定最好的方法是很困难的,但这可能会有所帮助:

var oData = {
    sections : [{name: "section1",
                items : {
                        item1 : {description : "description goes here", checked : true},
                        item2 : {description : "description goes here", checked : true} 
                        }
                },
                {name: "section2", 
                 items : {
                        item1 : {description : "description goes here", checked : true},
                        item2 : {description : "description goes here", checked : true} 
                        }
                 }
                ]}

【讨论】:

  • 这行得通,如何修改现有模型以使用此结构?
  • 我想我已经写了一个修改过的结构。您是在谈论主干代码中的模型吗?
  • 是的,对不起,我的意思是如何循环遍历原始结构来创建您提供的模型。
  • 好的,循环中的问题是您的 oData 不是有效的 json 甚至不是 javascript 对象文字。没有要循环的键或索引,因此无法实现。如果您能告诉我如何首先创建它,仍然可以做一些事情。 :)
猜你喜欢
  • 1970-01-01
  • 2017-02-14
  • 2017-12-22
  • 2021-10-02
  • 2019-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-26
相关资源
最近更新 更多