1

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.

7
  • What the point if an array of id if you're using only first item? Why no add a method to ExampleStruct and fetch first item. Commented Oct 9, 2017 at 11:34
  • There's a possibility that there's more than one id that could be added from the API call. I just added one for brevity. Commented Oct 9, 2017 at 11:36
  • more than one id that could be added and then if you call ExampleStruct.Added you still get the first item? Commented Oct 9, 2017 at 11:38
  • I have edited my question a little bit. If you see now, when I call ExampleStruct.Added, I should get a slice of strings in this format: ["1234ABCD", "5678EFGH"] Commented Oct 9, 2017 at 11:43
  • But Added is not a function, you cannot call it. Commented Oct 9, 2017 at 11:47

3 Answers 3

1

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
    }
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

1 Comment

No I tried that but it doesn't work because id is contained in the object which is contained in an array, and the array is the value of the add key of the JSON object.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.