doutuo3575
2016-02-23 02:31
浏览 59
已采纳

从Golang中的JSON字符串解码地图片段

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条回答 默认 最新

  • dth42345 2016-02-23 02:36
    已采纳

    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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongweng6241 2017-06-17 23:02

    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"`
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题