json 和类型转换

标签 json go

我正在尝试读取一个看起来像这样的 json 文件

 [{ "title": "hi", "tags": [1,2,3,4,5,6] }, {...}, {...}]

代码是这样的

 contentdat, err := ioutil.ReadFile("content.json")
 check(err)
 var content []interface{}
 err = json.Unmarshal(contentdat, &content)
 check(err)


for i, contentItem := range content {
    vertedContentItem := contentItem.(map[string]interface{})
    contentTags := vertedContentItem["tags"].([]interface{})
    contentItemTags := make([]int, len(contentTags))
    for i, ctv := range contentTags {
        contentItemTags[i] = int(ctv.(float64))
    }

我想弄清楚的是如何避免进行所有类型转换并直接访问 json obj 或者可能只对整个 json 结构进行一次类型转换。我想到了像这样定义内部对象的结构

type Content struct {
  title string
  tags []int
}

然后声明内容为

var content []Content

而不是 interface{} 并按预期循环遍历结构,但这没有用。有什么想法吗?

最佳答案

您必须使用大写字母导出您希望反序列化的“内容”结构的字段:

type Content struct {
  Title string
  Tags  []int
}

例如:

type Content struct {
  Title string
  Tags  []int
}

func main() {
  jsonstr := `[{"title":"hi","tags":[1,2,3,4,5,6]}]`
  contents := []Content{}

  err := json.Unmarshal([]byte(jsonstr), &contents)
  if err != nil {
    panic(err)
  }

  fmt.Printf("%#v\n", contents)
  // => []main.Content{main.Content{Title:"hi", Tags:[]int{1, 2, 3, 4, 5, 6}}}

}

关于json 和类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47912327/

相关文章:

json - 如何从嵌套数组中调用对象

go - 使用函数通过方法满足接口(interface)

amazon-web-services - 如何通过 AWS ALB 公开 API 以接收 zip 文件

json - Jenkins 多分支插件和远程 API

java - 从 dom 文档创建 json

python - Django 模板上的 Unicode 字符串显示

arrays - Golang graphql 使用子图迭代 map

go - 从Go lang的dynamodb表中获取所有唯一值

go - panic : errors: *target must be interface or implement error in Go

json - 如何读取服务状态并通过 bash 中的 JSON 将其传递到 Slack