Home  >  Article  >  Backend Development  >  Parse JSON array in golang using custom type

Parse JSON array in golang using custom type

WBOY
WBOYforward
2024-02-09 10:39:09670browse

使用自定义类型解析 golang 中的 JSON 数组

php editor Baicao brings you an article about parsing JSON arrays in golang. In golang, we can use custom types to parse complex JSON arrays. This approach not only enables better understanding and processing of JSON data, but also provides a more flexible way of operation. This article will introduce in detail how to use custom types to parse JSON arrays, and give some practical example codes to help you better understand and apply this technique. Whether you are a beginner or an experienced developer, you can benefit a lot from this article, come and explore together!

Question content

I am trying to parse a json array in golang, the format is as follows:

2beef840f8f9d8bb724c7736cb14989

For example, json should contain schemas for different tables. I have tried the following code but the schema returns empty:

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()
}

What did i do wrong? I would be grateful if you could point out my mistake Thanks!

Workaround

To match the source/destination JSON you can use the following types:

type Schema map[string][]ColumnType

Alternatively, you can use something easier to use:

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
}

The above is the detailed content of Parse JSON array in golang using custom type. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete