json.Unmarshal 不返回解码数据

标签 json go

<分区>

我在解码从 .json 文件中读取的 json 数据时遇到问题

type redisConfig struct {
    host string
    password string
}

func loadRedisConfig() (redisConfig, error){
    b, _ := ioutil.ReadFile("config.json")
    var config redisConfig
    fmt.Println(b)
    fmt.Println(string(b))


    e := json.Unmarshal(b, &config)

    fmt.Println(e)

    fmt.Println(config)
    return config, nil;
}

文件 config.json 包含以下内容:

{
  "host": "example.com",
  "password": "password"
}

我已经使用 http://jsonlint.com/ 验证它是有效的 JSON .在 SO 上阅读其他类似问题,我看到问题是无效的 json,我认为这里不是这种情况。

这是运行代码片段的输出:

[123 13 10 32 32 34 104 111 115 116 34 58 32 34 101 120 97 109 112 108 101 46 99 111 109 34 44 13 10 32 32 34 112 97 115 115 119 111 114 100 34 58 32 34 112 97 115 115 119 111 114 100 34 13 10 125]
{
  "host": "example.com",
  "password": "password"
}
<nil>
{ }

config 变量包含一个空结构,应该用文件和解码器提供的编码 json 填充它

最佳答案

Unmarshal只会设置结构的导出字段。
只需将字段公开(导出):

type redisConfig struct {
    Host     string
    Password string
}

使用 ioutil.ReadFile("config.json"):

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
)

func main() {
    b, err := ioutil.ReadFile("config.json")
    if err != nil {
        panic(err)
    }
    var config redisConfig
    err = json.Unmarshal(b, &config)
    if err != nil {
        panic(err)
    }
    fmt.Println(config)
}

type redisConfig struct {
    Host     string
    Password string
}

输出:

{example.com password123}

尝试 The Go Playground :

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    //The file config.json contains this:
    str := `{
  "host": "example.com",
  "password": "password123"
}`
    //b, _ := ioutil.ReadFile("config.json")
    b := []byte(str)
    var config redisConfig
    e := json.Unmarshal(b, &config)
    if e != nil {
        panic(e)
    }
    fmt.Println(config)
}

type redisConfig struct {
    Host     string
    Password string
}

输出:

{example.com password123}

关于json.Unmarshal 不返回解码数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39439863/

相关文章:

JSON API 规范 - 服务器职责说明

javascript - 无法理解 jQuery.parseJSON JSON.parse 回退

json - UnmarshalJSON 来自 []interface{} 的任何类型可能吗?

go - golang 中的依赖注入(inject)

go - "Memory used"公制 : Go tool pprof vs docker stats

go - 从 Golang 的阅读器中读取 < 8 位

java - 为什么我在尝试将 JSON 数据加载到 RecyclerView 时收到 NullPointerException?

python - 解析嵌套的Python字典

ssh - 使用 SSH 和带有 golang 的 pem/key 连接到服务器

mysql - 全局变量未传递到下一个包