我如何构建JSON?

时间:2018-06-11 19:53:42

标签: json

我有这个数据样本,我需要将其放入JSON格式。

这样做的最佳方法/结构是什么?如果它有帮助,我将为此开发一个角度产品选择工具。

Item 1: Federation Phaser
Options:
  | FORM FACTOR   | PRICE |
  | Compact             | $545  |
  | Pistol Grip          | $600  |

Item 2: Sith Lightsaber
Options:
  | BLADE COLOR | BLADE COUNT | PRICE |
  | Red                    | Single                 | $1000 |
  | Red                    | Double               | $1750 |
  | Blue                   | Single                 | $1125 |
  | Blue                   | Double                | $1875 |
  | Green                | Single                  | $1250 |

1 个答案:

答案 0 :(得分:2)

JSON由名称/值对组成,并由花括号{}包围。名称/值对用逗号分隔,值本身可以是JSON对象或数组。

示例1(简单):

{
  "fruit1": "apple",
  "fruit2": "pear"
}

示例2(更复杂):

{
  "fruitBasket1": { "fruit1": "apple", "fruit2": "pear"},
  "fruitBasket2": { "fruit1": "grape", "fruit2": "orange"}
}

对于您的示例,您可以使用数组构建JSON,如下所示:

{
    "item": {
        "name": "Federation Phaser",
        "options": [
            {
                "form": "compact",
                "price": "$545"
            },
            {
                "form": "Pistol Grip",
                "price": "$600"
            }
        ]
    },
    "item2": {
        "name": "Sith Lightsaber",
        "options": [
            {
                "bladeColor": "red",
                "count": "single",
                "price": "$1000"
            },
            {
                "bladeColor": "blue",
                "count": "double",
                "price": "$1875"
            }
        ]
    }
}

如果您想拥有可变数量的“项目”,您也可以将它们放入数组中。例如:

{
    "items": [
        {
            "name": "Federation Phaser",
            "options": [{
                    "form": "compact",
                    "price": "$545"
                },
                {
                    "form": "Pistol Grip",
                    "price": "$600"
                }
            ]
        },
        {
            "name": "Sith Lightsaber",
            "options": [{
                    "bladeColor": "red",
                    "count": "single",
                    "price": "$1000"
                },
                {
                    "bladeColor": "blue",
                    "count": "double",
                    "price": "$1875"
                }
            ]
        }
    ]
}