正确使用JSON进行简单的餐厅菜单描述

时间:2011-10-03 05:27:49

标签: javascript json validation encoding

我想知道我制作的这个JSON脚本示例是否格式正确,是否有意义放置这样的信息。

{"menu": {
  "drinks": [
    {"coke": "20"},
    {"pepsi": "20"},
    {"water": "20"}
  ],
  "junk-food": [
    {"hamburger": "40"},
    {"fries": "20"},
    {"pizza": "20"}
  ]
}}

我已经用http://jsonlint.com/验证了脚本,但是我还想再多说一点,因为我很新。

对于使用脚本的一些上下文,我将用Python解析脚本。

它旨在组织GUI的元素,这些元素看起来或多或少如下:

enter image description here

在第二个窗口中,将显示与第一个窗口类似的列表框,其中包含相应的项目和相应的价格。

  • JSON是否正确?
  • 这种结构有意义吗?

1 个答案:

答案 0 :(得分:4)

JSON是正确的。但结构没有太多的语义含义。我更改了结构,使其具有更多含义,并且在添加属性时更易于管理。

{"menu": {
    "items": [
        {
            "name":"coke",
            "qty": 20,
            "category":"drinks",
            "sizes":["small","large"]
        },
        {
            "name":"pepsi",
            "qty": 20,
            "category":"drinks",
            "sizes":["small","large"]
        },
        {
            "name":"water",
            "qty": 20,
            "category":"drinks",
            "sizes":["small","large"]
        },
        {
            "name":"hamburger",
            "qty": 40,
            "category":"junk food",
            "sizes":["small","large"]
        },
        {
            "name":"fries",
            "qty": 20,
            "category":"junk food",
            "sizes":["small","large"]
        },
        {
            "name":"pizza",
            "qty": 20,
            "category":"junk food",
            "sizes":["small","large"]
        }
    ]
}}

为了节省空间,你也可以做这样的事情,

{"menu": {
    "items": [
        {
            "name":"coke",
            "qty": 20,
            "category":0,
            "sizes":["small","large"]
        },
        {
            "name":"pepsi",
            "qty": 20,
            "category":0,
            "sizes":["small","large"]
        },
        {
            "name":"water",
            "qty": 20,
            "category":0,
            "sizes":["small","large"]
        },
        {
            "name":"hamburger",
            "qty": 40,
            "category":1,
            "sizes":["small","large"]
        },
        {
            "name":"fries",
            "qty": 20,
            "category":1,
            "sizes":["small","large"]
        },
        {
            "name":"pizza",
            "qty": 20,
            "category":1,
            "sizes":["small","large"]
        }
    ],
    "categories":[
        "drinks",
        "junk food"
    ]
}}