首页 > 解决方案 > 定义结构并将其编组为 json 的问题

问题描述

在 struct / json 字符串中表示以下内容的最佳方式是什么?-如果可能的话-

我想处理的数据看起来像:

{{Database : "flowers" ,  Type : "sunflower" - Location : "behind"
                                           - Height   : "130"
                     ,  Type : "roses"     - Time     : "12:30"
                                           - Date     : "12-12-2019"
                                           - Height   : "150" },
{
Database : "fruits"  ,  Type : "apple"     - Height   : "200"
                     ,  Type : "peer"      - Location : "above"
                     ,  Type : "banana"    - Color    : "green" }}

任何从哪里开始的提示或任何想法都将非常有帮助,非常感谢。

标签: jsongostruct

解决方案


There are many ways that you could represent this data in your code and in json, here is just a couple of ways you could section it dependent on what is important to you and what you would do with the data after it is in the structs/json.

type (
Plant struct {
    Type            string              `json:"type"`           //flowers or fruits
    Attributes      *PlantAttributes    `json:"attributes"`
}

PlantAttributes struct {
    Name            string              `json:"name"`           //apple or roses etc
    Location        string              `json:"location"`
    Height          string              `json:"height"`
    Time            string              `json:"time"`
    Date            string              `json:"date"`
    Color           string              `json:"color"`
}

)

or

type (
Flowers struct {
    Type            string                  `json:"type"`           // apples or bananas
    Attributes      *PlantAttributes        `json:"attributes"`
}

Fruit struct {
    Type            string                  `json:"type"`           // sunflowers or roses
    Attributes      *PlantAttributes        `json:"attributes"`
}

PlantAttributes struct {
    Location        string              `json:"location"`
    Height          string              `json:"height"`
    Time            string              `json:"time"`
    Date            string              `json:"date"`
    Color           string              `json:"color"`
}

)


推荐阅读