1

Following the Go by Example: JSON tutorial, I see how to work with a basic JSON string:

package main

import (
    "encoding/json"
    "fmt"
    )

type Response struct {
    Page   int      `json:"page"`
    Fruits []string `json:"fruits"`
}

func main() {
    str := `{"page": 1, "fruits": ["apple", "peach"]}`
    res := Response{}
    json.Unmarshal([]byte(str), &res)
    fmt.Println(res.Page)
    fmt.Println(res.Fruits)
}

// the output looks good here:
// 1
// [apple peach]

I would like to add some complexity to the str data object that I am decoding.

Namely, I would like to add a key with a slice of maps as its value:

"activities": [{"name": "running"}, {"name", "swimming"}]

My script now looks like below example, however, for the life of me, I can not figure out what the correct syntax is in the Response struct in order to get at the values in activities. I know that this syntax isn't correct: Activities []string ... but can not hack my way towards a solution that captures the data I want to display.

package main

import (
    "encoding/json"
    "fmt"
    )

type Response struct {
    Page   int      `json:"page"`
    Fruits []string `json:"fruits"`
    Activities []string `json:"activities"`
}

func main() {
    str := `{"page": 1, "fruits": ["apple", "peach"], "activities": [{"name": "running"}, {"name", "swimming"}]}`
    res := Response{}
    json.Unmarshal([]byte(str), &res)
    fmt.Println(res.Page)
    fmt.Println(res.Fruits)
    fmt.Println(res.Activities)
}

// the script basically craps out here and returns:
// 0
// []
// []

Thanks for any help!

2 Answers 2

4

Use []map[string]string:

type Response struct {
    Page   int      `json:"page"`
    Fruits []string `json:"fruits"`
    Activities []map[string]string `json:"activities"`
}

playground example

Always check and handle errors. The example JSON has a syntax error which is corrected in the playground example.

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

Comments

0

I know this is an old one, but i've recently written utility for generating exact go type from json input and in similar case you could give it a spin: https://github.com/m-zajac/json2go

For this particular example it generates from json:

{"page": 1, "fruits": ["apple", "peach"], "activities": [{"name": "running"}, {"name": "swimming"}]}

go type:

type Object struct {
    Activities  []struct {
        Name string `json:"name"`
    }   `json:"activities"`
    Fruits  []string    `json:"fruits"`
    Page    int     `json:"page"`
}

Comments

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.