gogofan
gogofan

Reputation: 563

JSON tag to decode into a struct in Golang

I have a JSON like this:

{
"add":[{"id": "1234ABCD"}, {"id": "5678EFGH"}]
}

And I have a struct like this:

type ExampleStruct struct {
    Added   []string
}

I am wondering what JSON tag I should put in my struct so that after I do the JSON decoding (code not shown here) and then call exampleStruct := &ExampleStruct followed by exampleStruct.Added, how can I get ["1234ABCD", "5678EFGH"]?

I tried doing this:

type ExampleStruct struct {
    Added   []string `json:"add"`
}

But it didn't work.

Upvotes: 1

Views: 2939

Answers (3)

Satyam Zode
Satyam Zode

Reputation: 185

You need to arrange your json such a way that elements of the struct should be accessible directly (without over-engineering it).

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
)

type ExampleStruct struct {
    Add []struct {
        ID string `json:"id"`
    } `json:"add"`
}

func main() {

    const code = `{
     "add":[{"id": "1234ABCD"}, {"id": "5678EFGH"}]
    }`

     var data ExampleStruct
     json.NewDecoder(bytes.NewReader([]byte(code))).Decode(&data)
     fmt.Println(data)           //Get all ids: {[{1234ABCD} {5678EFGH}]}
     fmt.Println(data.Add[0].ID) //Get 1st ID : 1234ABCD
     fmt.Println(data.Add[1].ID) //Get 2nd ID ... and so on.: 5678EFGH
}

You can find the code here https://play.golang.org/p/7tD4fLBewp .

If you have many ids in an array then you can also write a function to loop over the array i.e data.Addand get ids from that.

Upvotes: 0

gonutz
gonutz

Reputation: 5582

Use a slice of maps instead of strings, as you have key-value pairs of strings.

    type ExampleStruct struct {
        Added []map[string]string `json:"add"`
    }

Here is a full example:

    package main

    import (
        "bytes"
        "encoding/json"
        "fmt"
    )

    func main() {
        const code = `{
    "add":[{"id": "1234ABCD"}]
    }`
        type ExampleStruct struct {
            Added []map[string]string `json:"add"`
        }
        var data ExampleStruct
        json.NewDecoder(bytes.NewReader([]byte(code))).Decode(&data)
        fmt.Println(data)
    }

EDIT

Since you want to have only the values of the maps, here is a complete example where Added is a function that can be called on the ExampleStruct. It assumes that each map only contains two strings (id and value):

    package main

    import (
        "bytes"
        "encoding/json"
        "fmt"
    )

    func main() {
        const code = `{
    "add":[{"id": "1234ABCD"}, {"id": "5678EFGH"}]
    }`
        var data ExampleStruct
        json.NewDecoder(bytes.NewReader([]byte(code))).Decode(&data)
        fmt.Println(data)
        fmt.Println(data.Added())
    }

    type ExampleStruct struct {
        Add []map[string]string `json:"add"`
    }

    func (e ExampleStruct) Added() []string {
        values := make([]string, len(e.Add))
        for i := range e.Add {
            for _, v := range e.Add[i] {
                values[i] = v
            }
        }
        return values
    }

Upvotes: 1

mangeshbhuskute
mangeshbhuskute

Reputation: 140

have you tried to obtain its key by adding 'id', like this

type ExampleStruct struct { Added []string json:"add.id" }

Upvotes: 0

Related Questions