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的更多相关文章

  1. golang基础知识之文件操作

    读取文件所有内容以及获得文件操作对象 package mainimport ( "bufio" "fmt" "io" "io/io ...

  2. 数据结构和算法(Golang实现)(8.1)基础知识-前言

    基础知识 学习数据结构和算法.我们要知道一些基础的知识. 一.什么是算法 算法(英文algorithm)这个词在中文里面博大精深,表示算账的方法,也可以表示运筹帷幄的计谋等.在计算机科技里,它表示什么 ...

  3. 数据结构和算法(Golang实现)(8.2)基础知识-分治法和递归

    分治法和递归 在计算机科学中,分治法是一种很重要的算法. 字面上的解释是分而治之,就是把一个复杂的问题分成两个或更多的相同或相似的子问题. 直到最后子问题可以简单的直接求解,原问题的解即子问题的解的合 ...

  4. 数据结构和算法(Golang实现)(9)基础知识-算法复杂度及渐进符号

    算法复杂度及渐进符号 一.算法复杂度 首先每个程序运行过程中,都要占用一定的计算机资源,比如内存,磁盘等,这些是空间,计算过程中需要判断,循环执行某些逻辑,周而反复,这些是时间. 那么一个算法有多好, ...

  5. [BS-12] JSON的基础知识--百科

    JSON的基础知识--百科 http://baike.baidu.com/view/136475.htm

  6. Golang 入门系列(三)Go语言基础知识汇总

    前面已经了 Go 环境的配置和初学Go时,容易遇到的坑,大家可以请查看前面的文章 https://www.cnblogs.com/zhangweizhong/category/1275863.html ...

  7. golang encoding/json

    package main import ( "bytes" "encoding/json" "fmt" ) type ColorGroup ...

  8. 数据结构和算法(Golang实现)(10)基础知识-算法复杂度主方法

    算法复杂度主方法 有时候,我们要评估一个算法的复杂度,但是算法被分散为几个递归的子问题,这样评估起来很难,有一个数学公式可以很快地评估出来. 一.复杂度主方法 主方法,也可以叫主定理.对于那些用分治法 ...

  9. JSON基础知识总结

    JSON基础 一.JSON简介 JSON,全称“JavaScript Object Notation(JavaScript对象表示法)”,起源于JavaScript的对象和数组.JSON,说白了就是J ...

随机推荐

  1. php上传文件大小限制修改

    打开php.ini 1.最大上传文件大小: upload_max_filesize=2M 改成自己需要的大小 2.最大post大小: post_max_size=2M 改成自己需要的大小,第二个一般比 ...

  2. 求教Sublime Text2 SublimeLinter插件安装问题

    昨天装了 SublimeLinter插件(代码语法检测),这个事插件的地址:https://github.com/Kronuz/SublimeLinter 按照作者的介绍配置了一下,发现语法检测不起作 ...

  3. 【云计算】Cloudify-基于TOSCA规范的开源云应用编排系统

      .cloudify-manager-blueprints:https://github.com/cloudify-cosmo/cloudify-manager-blueprints/tree/3. ...

  4. 项目中Ajax调用ashx页面中的Function的实战

    前台页面: 使用几个display=none的空间存储DropdownList中的值,点击Search Button后刷新页面再次给DropdownList赋值使用 <%@ Page Langu ...

  5. 将数据导入带模板EXCEL

    在EXCEL模板里设置好样式和格式 点击事件 private void btnReport_Click(object sender, EventArgs e)        {            ...

  6. SharePoint2010母版页想要的定制

    查找<div id="s4-ribbonrow" class="s4-pr s4-ribbonrowhidetitle"用style="disp ...

  7. 解决Django发送中文邮件时的编码及乱码问题

    参考自---http://blog.csdn.net/clh604/article/details/9274793 #-*- coding=utf8 -*- from email.message im ...

  8. struts2 结果页面配置

    <result>标签: * 属性: * name:逻辑视图的名称 * type:结果页面类型. * dispatcher         :转发.默认值. * redirect       ...

  9. Starting MySQL.The server quit without updating PID file (xxxx.pid).[FAILED]

    mysql无法正常启动,查看日志报如下异常 --07T01::.929615Z [ERROR] Fatal error: Please read "Security" sectio ...

  10. ios Unit test 入门书籍推荐

    请参考 ios 7 by tutorials 中的 chapter 11 :Unit Testing in xcode 5