golang基础知识之encoding/json package
golang基础知识之json
简介
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式。可以去json.org 查看json标准的清晰定义。json package 是GO 语言官方提供的包,后续会提供开源实现json package的分析。
Encoding
func Marshal(v interface{}) ([]byte, error)
基本类型
bolB, _ := json.Marshal(true) fmt.Println(string(bolB)) intB, _ := json.Marshal(1) fmt.Println(string(intB)) fltB, _ := json.Marshal(2.34) fmt.Println(string(fltB))
output:
true 1 2.34 "gopher"
自定义类型的序列化
type Response1 struct { Page int Fruits []string}// The JSON package can automatically encode your// custom data types. It will only include exported// fields in the encoded output and will by default// use those names as the JSON keys.res1D := &Response1{ Page: 1, Fruits: []string{"apple", "peach", "pear"}}res1B, _ := json.Marshal(res1D)fmt.Println(string(res1B))
只会将可外部访问的字段序列化到json里面去
能够以JSON形式呈现的数据结构才能被encode:
由于JSON 对象只支持strings 为key,Go map 类型必须以map[string]T的形式
Channel,复杂的和function无法被encode
循环的数据结构不支持
指针会按照指向的值被encode
Decoding
func Unmarshal(data []byte, v interface{}) errorb := []byte(`{"Name":"Bob","Food":"Pickle"}`)var m Messageerr := json.Unmarshal(b, &m)
对于结构中不是外部可访问的字段或者缺少的字段,反序列化会自动忽略该字段
使用interface{} 处理通用的json
b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)var f interface{}err := json.Unmarshal(b, &f)b := []byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`)var f interface{}err := json.Unmarshal(b, &f)if err != nil { panic(err)}m := f.(map[string]interface{})for k, v := range m { switch vv := v.(type) { case string: fmt.Println(k, "is string", vv) case int: fmt.Println(k, "is int", vv) case []interface{}: fmt.Println(k, "is an array:") for i, u := range vv { fmt.Println(i, u) } default: fmt.Println(k, "is of a type I don't know how to handle") }}
Streaming Encoders and Decoders
package mainimport ( "encoding/json" "log" "os")func main() {dec := json.NewDecoder(os.Stdin)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 != "Name" { delete(v, k) } } if err := enc.Encode(&v); err != nil { log.Println(err) }}}
参见:
http://blog.golang.org/json-and-gohttps://golang.org/pkg/encoding/json/#pkg-examples
备注:
这个系列不是一个大而全的package api 指南,只包括作者认为最常见的使用方式,抗议无效。
golang基础知识之encoding/json package的更多相关文章
- golang基础知识之文件操作
读取文件所有内容以及获得文件操作对象 package mainimport ( "bufio" "fmt" "io" "io/io ...
- 数据结构和算法(Golang实现)(8.1)基础知识-前言
基础知识 学习数据结构和算法.我们要知道一些基础的知识. 一.什么是算法 算法(英文algorithm)这个词在中文里面博大精深,表示算账的方法,也可以表示运筹帷幄的计谋等.在计算机科技里,它表示什么 ...
- 数据结构和算法(Golang实现)(8.2)基础知识-分治法和递归
分治法和递归 在计算机科学中,分治法是一种很重要的算法. 字面上的解释是分而治之,就是把一个复杂的问题分成两个或更多的相同或相似的子问题. 直到最后子问题可以简单的直接求解,原问题的解即子问题的解的合 ...
- 数据结构和算法(Golang实现)(9)基础知识-算法复杂度及渐进符号
算法复杂度及渐进符号 一.算法复杂度 首先每个程序运行过程中,都要占用一定的计算机资源,比如内存,磁盘等,这些是空间,计算过程中需要判断,循环执行某些逻辑,周而反复,这些是时间. 那么一个算法有多好, ...
- [BS-12] JSON的基础知识--百科
JSON的基础知识--百科 http://baike.baidu.com/view/136475.htm
- Golang 入门系列(三)Go语言基础知识汇总
前面已经了 Go 环境的配置和初学Go时,容易遇到的坑,大家可以请查看前面的文章 https://www.cnblogs.com/zhangweizhong/category/1275863.html ...
- golang encoding/json
package main import ( "bytes" "encoding/json" "fmt" ) type ColorGroup ...
- 数据结构和算法(Golang实现)(10)基础知识-算法复杂度主方法
算法复杂度主方法 有时候,我们要评估一个算法的复杂度,但是算法被分散为几个递归的子问题,这样评估起来很难,有一个数学公式可以很快地评估出来. 一.复杂度主方法 主方法,也可以叫主定理.对于那些用分治法 ...
- JSON基础知识总结
JSON基础 一.JSON简介 JSON,全称“JavaScript Object Notation(JavaScript对象表示法)”,起源于JavaScript的对象和数组.JSON,说白了就是J ...
随机推荐
- ndk学习14: 进程
Linux进程管理 来自为知笔记(Wiz)
- Python读取中文txt文件错误:UnicodeEncodeError: 'gbk' codec can't encode character
with open(file,'r') as f: line=f.readline() i=1 while line: line=line.decode('utf-8') line=f.readlin ...
- 【GoLang】GoLang 单元测试、性能测试使用方法
单元测试代码: ackage test import ( // "fmt" "testing" ) func Test_FlowControl(t *testi ...
- Light OJ 1068
数位DP #include <cstdio> #include <cstring> using namespace std; ; ; long long n; int f[MA ...
- Java for LeetCode 234 Palindrome Linked List
解题思路: O(1)的空间复杂度,意味着不能通过开一个List来解决问题.我们可以把List分成前后两个部分,后半部分通过指针的相互赋值进行翻转即可. JAVA实现如下: public static ...
- Effective C++ -----条款41:了解隐式接口和编译期多态
classes和templates都支持接口(interface)和多态(polymorphism). 对classes而言接口是显式的(explicit),以函数签名为中心.多态则是通过virtua ...
- 【python】入门学习(十)
#入门学习系列的内容均是在学习<Python编程入门(第3版)>时的学习笔记 统计一个文本文档的信息,并输出出现频率最高的10个单词 #text.py #保留的字符 keep = {'a' ...
- HDU 5833 Zhu and 772002 (数论+高斯消元)
题目链接 题意:给定n个数,这n个数的素因子值不超过2000,从中取任意个数使其乘积为完全平方数,问有多少种取法. 题解:开始用素筛枚举写了半天TLE了,后来队友说高斯消元才想起来,果断用模板.赛后又 ...
- java获取手机号归属地
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import ...
- Yahoo!网站性能最佳体验的34条黄金守则(转载)
1. 尽量减少HTTP请求次数 终端用户响应的时间中,有80%用于下载各项内容.这部分时间包括下载页面中的图像.样式表.脚本.Flash等.通过减少页面中的元素可以减少HTTP请求的次数 ...