返回首页 - Notes - 2017

Go 语言处理 JSON


概述

处理 JSON,在 PHPRuby 这类脚本语言里面,也就是调用一个函数的事

但在 Go 这类编译型的静态语言里面,处理起来就有点繁琐了,需要自己先定义好 JSON 数据的结构,才能进行后续处理


准备工作

先预备一个名为 infos.json 的文件,内容是:

[
  {
    "name": "张三",
    "age": 18,
    "contact": {
      "email": "zhangsan@email.com",
      "phone": "13800138001"
    }
  },
  {
    "name": "李四",
    "age": 19,
    "contact": {
      "email": "lisi@email.com",
      "phone": "13800138002"
    }
  },
  {
    "name": "王五",
    "age": 20,
    "contact": {
      "email": "wangwu@email.com",
      "phone": "13800138003"
    }
  }
]

同时在本地运行一个服务器,确保可以通过 http://127.0.0.1:9999/infos.json 访问到该文件


解析 JSON

从字符串获取并解析

package main

import (
  "encoding/json"
  "fmt"
  "log"
)

// 定义 JSON 的结构
type Info struct {
  Name    string `json:"name"`
  Age     int    `json:"age"`
  Contact struct {
    Email string `json:"email"`
    Phone string `json:"phone"`
  } `json:"contact"`
}

func main() {
  content := `[
    {
      "name": "张三",
      "age": 18,
      "contact": {
        "email": "zhangsan@email.com",
        "phone": "13800138001"
      }
    },
    {
      "name": "李四",
      "age": 19,
      "contact": {
        "email": "lisi@email.com",
        "phone": "13800138002"
      }
    },
    {
      "name": "王五",
      "age": 20,
      "contact": {
        "email": "wangwu@email.com",
        "phone": "13800138003"
      }
    }
  ]`

  // 从字符串读取
  buf := []byte(content)

  // 解析 JSON 字符串
  var infos []Info
  err := json.Unmarshal(buf, &infos)
  if err != nil {
    log.Println("错误:", err)
    return
  }

  fmt.Println(infos)
}

从文件获取并解析

package main

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

// 定义 JSON 的结构
type Info struct {
  Name    string `json:"name"`
  Age     int    `json:"age"`
  Contact struct {
    Email string `json:"email"`
    Phone string `json:"phone"`
  } `json:"contact"`
}

func main() {
  // 从文件读取
  buf, err := ioutil.ReadFile("infos.json")
  if err != nil {
    log.Println("错误:", err)
    return
  }

  // 解析 JSON 字符串
  var infos []Info
  err = json.Unmarshal(buf, &infos)
  if err != nil {
    log.Println("错误:", err)
    return
  }

  fmt.Println(infos)
}

从远程获取并解析

package main

import (
  "encoding/json"
  "fmt"
  "log"
  "net/http"
)

// 定义 JSON 的结构
type Info struct {
  Name    string `json:"name"`
  Age     int    `json:"age"`
  Contact struct {
    Email string `json:"email"`
    Phone string `json:"phone"`
  } `json:"contact"`
}

func main() {
  url := "http://127.0.0.1:9999/infos.json"

  // 从 URL 读取
  resp, err := http.Get(url)
  if err != nil {
    log.Println("错误:", err)
    return
  }
  defer resp.Body.Close()

  // 解析 JSON 字符串
  var infos []Info
  err = json.NewDecoder(resp.Body).Decode(&infos)
  if err != nil {
    log.Println("错误:", err)
    return
  }

  fmt.Println(infos)
}

编码 JSON

package main

import (
  "encoding/json"
  "fmt"
  "log"
)

func main() {
  p1 := map[string]interface{}{
    "name": "张三",
    "age":  18,
    "contact": map[string]interface{}{
      "email": "zhangsan@email.com",
      "phone": "13800138001",
    },
  }

  p2 := map[string]interface{}{
    "name": "李四",
    "age":  19,
    "contact": map[string]interface{}{
      "email": "lisi@email.com",
      "phone": "13800138002",
    },
  }

  p3 := map[string]interface{}{
    "name": "李四",
    "age":  19,
    "contact": map[string]interface{}{
      "email": "lisi@email.com",
      "phone": "13800138002",
    },
  }

  content := []interface{}{p1, p2, p3}

  data, err := json.MarshalIndent(content, "", "  ")
  if err != nil {
    log.Println("错误:", err)
    return
  }

  fmt.Println(string(data))
}

date:2017-06-26