golang读取json文件

golang读取json数据

json文件:

{
	"hostUrl":"wss://spark-api.xf-yun.com/v2.1/chat",
	"appid":"your appid",
	"apiSecret":"your apiSecret",
	"apiKey":"your apiKey"
}

代码:

package main

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

var (
	hostUrl   = ""
	appid     = ""
	apiSecret = ""
	apiKey    = ""
)

func main() {
	// Let's first read the `config.json` file
	content, err := ioutil.ReadFile("D:\\golang_Start\\GPT\\Security.json")
	if err != nil {
		log.Fatal("Error when opening file: ", err)
	}

	// Now let's unmarshall the data into `payload`
	var payload map[string]string
	json.Unmarshal(content, &payload)

	hostUrl = payload["hostUrl"]
	appid = payload["appid"]
	apiSecret = payload["apiSecret"]
	apiKey = payload["apiKey"]

	// Let's print the unmarshalled data!
	log.Printf("hostUrl: %s\n", hostUrl)
	log.Printf("appid: %s\n", appid)
	log.Printf("apiSecret: %s\n", apiSecret)
	log.Printf("apiKey: %s\n", apiKey)
}

参考 https://juejin.cn/post/7117185445842141220

你可能感兴趣的:(golang,读取文件)