GoLang - 编解码JSON数据/读写JSON数据

前言

         Go语言内建对 JSON 的支持,使用内置的 encoding/json 标准库,开发人员可以轻松使用Go程序生成和解析 JSON 格式的数据。

 

干货

(1)将json入文件

package main

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

type Website struct {
	Name   string `json:"name"`
	Url    string
	Course []string
}

func main() {
	info := []Website{{"Golang", "http://c.biancheng.net/golang/", []string{"http://c.biancheng.net/cplus/", "http://c.biancheng.net/linux_tutorial/"}}, {"Java", "http://c.biancheng.net/java/", []string{"http://c.biancheng.net/socket/", "http://c.biancheng.net/python/"}}}

	// create json file
	filePtr, err := os.Create("info.json")
	if err != nil {
		Println("create 'info.json' failed! ", err.Error())
		return
	}
	defer filePtr.Close()

	// create json encoder
	encoder := json.NewEncoder(filePtr)

	// encode json string
	err = encoder.Encode(info)
	if err != nil {
		Println("encode failed! ", err.Error())
	}; println("encode ok.")
	time.Sleep(time.Second * 5)
}

 

(2)从文件中json并保存到结构体

package main

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

type Website struct {
	Name   string `json:"name"`
	Url    string
	Course []string
}

func main() {
	// open json file
	filePtr, err := os.Open("./info.json")
	if err != nil {
		Println("Open json file failed! ", err.Error())
	}
	defer filePtr.Close()

	// create json decoder
	decoder := json.NewDecoder(filePtr)

	// decode json string
	var info []Website
	err = decoder.Decode(&info)
	if err != nil {
		Println("Decode json failed! ", err.Error())
	}; Println("Decode json ok.\n JSON:", info)
	time.Sleep(time.Second * 5)
}

 

后话

          其实关于JSON的构建和解析还有一种方法,分别通过Marshal()UnMarshal()方法也能达到目的,这个且听下回分解~

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值