我正在try 用Golang解析一个json数组,格式如下:

[
  {
    "table1": [
      { "name": "col1", "type": "string"},
      { "name": "col2", "type": "int"},
    ]
  },
  {
    "table2": [
       { "name": "col3", "type": "string"},
       { "name": "col4", "type": "int"},
    ]
  },
  {
    "table3": [
      ...
    ]
  }
]

例如,json应该包含不同表的模式. 我try 了以下代码,但架构返回空:

package main

import (
    "encoding/json"
    "io"
    "log"
    "os"
)

type ColumnType struct {
    Name  string `json:"name"`
    Type  string `json:"type"`
}

type Schema struct {
    Schema map[string][]ColumnType
}

func main() {

    mocksSchemas, _ := os.Open("parse_config/mock_schema.json")

    var schemas []Schema
    content, err := io.ReadAll(mocksSchemas)
    if err != nil {
        log.Fatal("Error when reading mock file: ", err)
    }
    err = json.Unmarshal(content, &schemas)
    if err != nil {
        log.Fatal("Error during Unmarshal(): ", err)
    }

    defer mocksSchemas.Close()
}

我做错了什么?如果能帮我指出我的错误,我将不胜感激 谢谢!

推荐答案

要匹配源/目标JSON,您可以使用以下类型:

type Schema map[string][]ColumnType

或者,您也可以使用一些更易于用途:

type Schema struct {
    Table   string
    Columns []ColumnType
}

func (s Schema) MarshalJSON() ([]byte, error) {
    return json.Marshal(map[string][]ColumnType{
        s.Table: s.Columns,
    })
}

func (s *Schema) UnmarshalJSON(data []byte) error {
    var m map[string][]ColumnType
    if err := json.Unmarshal(data, &m); err != nil {
        return err
    }
    for k, v := range m {
        s.Table = k
        s.Columns = v
        break
    }
    return nil
}

Json相关问答推荐

ArcGIS json到Geojson的变换

NiFi QueryRecord处理器- Select 可选的JSON属性

在 PowerShell 中通过 aws cli 创建 cloudwatch alert 时出现字符串解析错误

如何在 Apache NiFi 中使用 JoltTransformJson 删除流文件或具有空字段的整个对象?

从 oracle 数据库中的 json blob 打印值

JSON 的自定义编组器,可以是字符串或 map[string]string / map[string]bool

父键中的 Perl JSON 数组

shell解析json并循环输出组合变量

避免 KeyError 的默认字典键

JSON 模式验证

单元测试球衣 Restful Services

Python Flask-Restful POST 不采用 JSON 参数

.NET CORE 3 升级 CORS 和 Json(cycle) XMLHttpRequest 错误

谷歌浏览器不允许我放置断点

使用 Spring 和 JsonTypeInfo 注释将 JSON 反序列化为多态对象模型

如何在 MVC4 中将 Json 字符串输出为 JsonResult?

从 VS 2017 Azure Function 开发中的 local.settings.json 读取值

处理 HTTP 请求正文中的可选 JSON 字段

Jersey 2.0 相当于 POJOMappingFeature

XML vs YAML vs JSON