Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map JSON array value to struct specific variable

Tags:

json

go

Let's say I have this JSON structure:

{
"name":"repo",
"tags":["1.0","2.0","3.0"]
}

And I would like to map it to this Go struct:

type Repository struct {
    Name string `json:"name"`
    Tags []struct {
        Tag   string `json:"??"`
        Sha256 string
    }
}

How can I link the "tags" array JSON value to a struct field?

EDIT: The idea will be to access the tags array value like this repository.Tags[0].Tag.

like image 954
dsncode Avatar asked Sep 22 '26 00:09

dsncode


1 Answers

Implement json.Unmarshaler on a Tag type:

package main

import (
    "encoding/json"
    "log"
)

type Repository struct {
    Name string
    Tags []Tag
}

type Tag struct {
    Tag    string
    Sha256 string
}

func (t *Tag) UnmarshalJSON(b []byte) error {
    var s string

    if err := json.Unmarshal(b, &s); err != nil {
            return err
    }

    t.Tag = s
    return nil
}

func main() {
    b := []byte(`{ "name":"repo", "tags":["1.0","2.0","3.0"] }`)

    var r Repository
    err := json.Unmarshal(b, &r)
    if err != nil {
            log.Fatal(err)
    }

    log.Printf("%+v\n", r)
}

Try it on the playground: https://play.golang.org/p/ExwWhis0w0V

Marshaling back to JSON is left as an exercise for the reader.

like image 161
Peter Avatar answered Sep 24 '26 14:09

Peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!