Json处理

基础

使用json.Marshal()函数可以对一组数据进行JSON格式的编码

func Marshal(v interface{}) ([]byte, error)

可以使用json.Unmarshal()函数将JSON格式的文本解码为Go里边预期的数据结构。json.Unmarshal()函数的原型如下:

func Unmarshal(data []byte, v interface{}) error

解码未知结构的JSON数据

JSON中的布尔值将会转换为Go中的bool类型;

 数值会被转换为Go中的float64类型;

 字符串转换后还是string类型;

 JSON数组会转换为[]interface{}类型;

 JSON对象会转换为map[string]interface{}类型;

 null值会转换为nil。

package main

import (
	"fmt"
	"encoding/json"
)
func main() {
	b := []byte(`{
	"Title": "Go语言编程",
	"Authors": ["XuShiwei", "HughLv", "Pandaman", "GuaguaSong", "HanTuo", "BertYuan","XuDaoli"],
	"Publisher": "ituring.com.cn",
	"IsPublished": true,
	"Price": 9.99,
	"Sales": 1000000
	}`)
	var r interface{}
	err := json.Unmarshal(b, &r)
	if err != nil{
		return
	}
	gobook, ok := r.(map[string]interface{})//需要先判断目标结构是否为预期的数据类型
	if ok {
		for k, v := range gobook {
			switch v2 := v.(type) {//也是断言,判断v的类型,为了判断interface的实体类型而设置的
			case string:
				fmt.Println(k, "is string", v2)
			case int:
				fmt.Println(k, "is int", v2)
			case bool:
				fmt.Println(k, "is bool", v2)
			case []interface{}:
				fmt.Println(k, "is an array:")
				for i, iv := range v2 {
					fmt.Println(i, iv)
				}
			default:
				fmt.Println(k, "is another type not handle yet")
			}
		}
	}
}

json从标准输入流读取json数据并解码

Go内建的encoding/json 包还提供Decoder和Encoder两个类型,用于支持JSON数据的流式读写,并提供NewDecoder()和NewEncoder()两个函数来便于具体实现:

func NewDecoder(r io.Reader) *Decoder

func NewEncoder(w io.Writer) *Encoder
func readJsonFromOs(){
	dec := json.NewDecoder(os.Stdin)//输入的Json数据必须以{}为开始和结尾
	enc := json.NewEncoder(os.Stdout)
	for {
		var v map[string]interface{}
		if err := dec.Decode(&v); err != nil {
			log.Println(err)
			return
		}
		for k:= range v {
			if k != "Title" {
				v[k] = nil
			}
		}
		if err := enc.Encode(&v); err != nil {
			log.Println(err)
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值