json.Unmarshal json string to object is empty 结果

标签 json object go marshalling

<分区>

我有一个像这样的非常简单的程序:

package main

import (
    "encoding/json"
    "fmt"
)

type RunCommand struct{
    level string `json:"level"`
    caller string `json:"caller"`
    msg string `json:"msg"`
    cmd string `json:"cmd"`
}

func main() {
    content := `{"level":"info","caller":"my.go:10","msg":"run","cmd":"--parse"}`
    runCommand := RunCommand{}
    e := json.Unmarshal([]byte(content), &runCommand)
    if e != nil {
        fmt.Println("Unmarshal error")
    }
    fmt.Println(runCommand.level)
}

我希望我可以将“content”中的所有 json 字段解析为“runCommand”对象,但实际上,最终的“fmt.Println”什么也不打印。我哪里错了?

最佳答案

你必须有导出字段,像这样:

type RunCommand struct{
    Level string `json:"level"`
    Caller string `json:"caller"`
    Msg string `json:"msg"`
    Cmd string `json:"cmd"`
}

现在您可以使用:fmt.Println(runCommand.Level) 否则 json.Unmarshal 将忽略未导出的字段。

关于json.Unmarshal json string to object is empty 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57908166/

相关文章:

ios - 如果 objectForKey 包含单个值,则在计数时抛出异常

javascript - 将本地 JSON 文件读入变量

javascript - 如何根据时间对对象数组进行排序?

戈朗 : Opposite of Append to remove data

java - 从服务器接收响应时出错?

Javascript 从 1 个对象创建 2 个实例

java - 如何根据值用对象参数填充数组?

go - 在 golang 中获取日期,例如 "2018-07-13"

go - 为什么建议在 go 中返回 `error` 接口(interface)而不是具体的错误类型?

json - 无法通过其 mediaLink 从 Google Cloud Storage 检索对象