3

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.

2
  • 1
    mholt.github.io/json-to-go Commented Mar 15, 2018 at 7:41
  • but I want to map the value to a struct Tag value. So I can call it like repository.Tags[0].tag Commented Mar 15, 2018 at 7:43

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

5 Comments

super, it works! But I was wondering if there was a "out of the box" approach. like adding json:"" or something like that.
@dsncode you are trying to unmarshal an array into struct which don't have keys. You needs to tell the json Unmarshaler how to map array values to struct
@dsncode, no, there is not. The stdlib can only map JSON documents to Go types one-to-one, if that makes sense. Everything else has to be done with the json.Marshaler and json.Unmarshaler interfaces.
@Peter this is interesting, and I was wondering how and where this UnmarshalJSON called ?
@GujaratSantana, the encoding/json package calls it when unmarshaling a value of type Tag: golang.org/pkg/encoding/json/#Unmarshaler

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.