如何多天和多次使用嵌套数组数组创建JSON对象?

时间:2012-11-17 07:08:51

标签: json

我正在尝试创建一个JSON目标文件,但我不确定如何记录所有可用的滑冰课程列表。目前我有以下内容:

[
{"classname":"FS1","classdays":["monday", "wednesday"]},
{"classname":"FS2","classdays":  ["tuesday", "thursday"]}
]

它有效,唯一的问题是每个类“classname”,每天“classdays”有多个classtimes。而且我不确定如何添加另一个数组并将它们与特定类的特定日期相关联,并将其添加到我当前的JSON文件中以创建该结构。

以下是非编程语言的类 - 为清晰起见:

Classname: FS1
Monday classes are 12:00PM and 2:00PM
Wednesday classes are 1:00PM and 3:00PM
Classname: FS2
Tuesday classes are 4:00PM and 6:00PM
Thursday classes are 2:00PM and 8:00PM
Classname: FS3
Monday classes are 2:00PM and 4:00PM
Thursday classes are 2:00PM and 8:00PM

我愿意接受有关如何最好地构建或根据需要进行重组的建议。

3 个答案:

答案 0 :(得分:1)

classdays中的每个条目设为一个对象,并将日期名称和时间作为键:

[
    {
        "classname": "FS1",
        "classdays": [
            {
                "day": "monday",
                "times": [
                    "12:00",
                    "14:00"
                ]
            },
            {
                "day": "tuesday",
                "times": [
                    "16:00",
                    "18:00"
                ]
            },
            ...more days here...
        ]
    },
    ...more classses here...
]

可以使classdays成为一个对象而不是一个数组,以日期名称键入:

[
    {
        "classname": "FS1",
        "classdays": {
            "monday": [
                "12:00",
                "14:00"
            ],
            "tuesday": [
                "16:00",
                "18:00"
            ],
            ...more days here...
        }
    },
    ...more classes here...
]

......但是那天没有秩序。当然,我希望你的代码的逻辑可以知道一周中的日期是什么顺序,但我想我可能会使用第一个结构。

答案 1 :(得分:1)

首先,只是指出JSON不是“编程语言”,它是一种数据语言。区别在于JSON,就像XML一样它只描述对象的任何东西。

其次,我认为你前进的方向将直接让你认识到JSON不是关系型的。

最后,我会这样做:

[
    { "classname":"FS1",
      "classdays":[
        { "classday":"Monday",
          "classtimes": ["12:00 PM", "2:00 PM"]
        }, 
        { "classday":"Wednesday",
          "classtimes": ["1:00 PM", "3:00 PM"]
        }
        ]
    },
    { "classname":"FS2",
      "classdays":[
        { "classday":"Tuesday",
          "classtimes": ["4:00 PM", "6:00 PM"]
        }, 
        { "classday":"Thursday",
          "classtimes": ["2:00 PM", "8:00 PM"]
        }
        ]
    },
    ... And so on.
]

答案 2 :(得分:0)

{"classname":"FS1","classdays":[{"day":"monday","times":["12:00PM","2:00PM"]},{"day":"wednesday","times":["1:00PM","3:00PM"]}]}