douxuanwei1980 2017-04-10 05:40
浏览 60
已采纳

在Go中读取json文件值[重复]

This question already has an answer here:

I have a config file. I want to get specific value from that file. Here is my code :

package main

import (
    "fmt"
    "os"
    "encoding/json"
)

type Configuration struct {
    consumer_key   string
    consumer_secret   string
    access_token   string
    access_token_secret   string
    db_name   string
    db_user   string
    db_password   string
    secret_key   string
    fb_page   string
    fb_page_token   string
    domain   string
}

func main() {
    file, _ := os.Open("./config.json")
    decoder := json.NewDecoder(file)
    configuration := Configuration{}
    error_ := decoder.Decode(&configuration)
     fmt.Println(configuration.domain)
}

config.json

{
  "consumer_key": "",
  "consumer_secret": "",
  "access_token": "",
  "access_token_secret": "",
  "db_name": "",
  "db_user": "",
  "db_password": "",
  "secret_key": "",
  "fb_page": "",
  "fb_page_token": "",
  "domain": "localhost:8000"
}

But the problem is it always print empty line, not the value localhost:8000 I am expecting.

</div>
  • 写回答

1条回答 默认 最新

  • duanpuqi9965 2017-04-10 05:44
    关注

    You need to export Configuration.domain field so that json package can see it.

    Rename the domain field to Domain:

    type Configuration struct {
      Domain string
    }
    

    You can also specify json name explicitly if it differs from field name:

    type Configuration struct {
      Domain string `json:"domain_name"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100