Golang: 解析JSON数据之一

// 读取JSON文件 将内容转为结构对象 然后更改数据

package main

import (
    "encoding/json"
    "fmt"
)

type (
    person struct {
        Name string `json:"name"`
        Age  int    `json:"age"`
    }

    result struct {
        Group   string   `json:"group"`
        Persons []person `json:"persons"`
    }
)

var jsondata = `{
  "group": "programmer",
  "persons": [
    {
      "name": "Jack",
      "age": 25
    },
    {
      "name": "Lily",
      "age": 20
    }
  ]
}`

func main() {
    var data result

    // 读取JSON文件内容 返回字节切片
    bytes := []byte(jsondata)

    fmt.Println("*** data.json content: ***")

    // 打印时需要转为字符串
    fmt.Println(string(bytes))

    // 将字节切片映射到指定结构上
    json.Unmarshal(bytes, &data)

    fmt.Println("*** unmarshal result: ***")

    // 打印对象结构
    fmt.Println(data)

    // 更改数据
    data.Group = "engineer"
    data.Persons[0].Age = -100

    // 将更改后的结构对象序列化成JSON格式
    newBytes, _ := json.Marshal(&data)

    fmt.Println("*** update content: ***")

    // 打印JSON结果
    fmt.Println(string(newBytes))
}

 

参考:https://www.cnblogs.com/liuhe688/p/10971327.html

 

用以下网址返回的json写个实例:

   http://quotes.money.163.com/hs/service/diyrank.php?host=http%3A%2F%2Fquotes.money.163.com%2Fhs%2Fservice%2Fdiyrank.php&page=0&query=STYPE%3AEQA&fields=SYMBOL%2CNAME%2CPRICE&sort=SYMBOL&order=asc&count=8&type=query

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

type (
    ListOne struct {
        NAME   string  `json:"NAME"`
        SYMBOL string  `json:"SYMBOL"`
        PRICE  float64 `json:"PRICE"`
    }

    result struct {
        Page  int       `json:"page"`
        Order string    `json:"order"`
        Time  int       `json:"time"`
        List  []ListOne `json:"list"`
    }
)

func main() {
    var data result

    url := "http://quotes.money.163.com/hs/service/diyrank.php?host=http%3A%2F%2Fquotes.money.163.com%2Fhs%2Fservice%2Fdiyrank.php&page=0&query=STYPE%3AEQA&fields=SYMBOL%2CNAME%2CPRICE&sort=SYMBOL&order=asc&count=8&type=query"
    req, _ := http.NewRequest("GET", url, nil)
    // 设置header
    req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1;WOW64) AppleWebKit/537.36 (KHTML,like GeCKO) Chrome/45.0.2454.85 Safari/537.36 115Broswer/6.0.3")
    req.Header.Set("Referer", "https://movie.douban.com/")
    req.Header.Set("Connection", "keep-alive")
    resp, err := (&http.Client{}).Do(req)
    if err != nil {
        panic(err)
    }
    // 读取JSON文件内容 返回字节切片
    bytes, _ := ioutil.ReadAll(resp.Body)

    // 将字节切片映射到指定结构上
    json.Unmarshal(bytes, &data)

    // 打印对象结构
    fmt.Println(data)
    fmt.Println(data.List[1].NAME)

}

 

Golang: 解析JSON数据之一

上一篇:兼容ie浏览器的html、js和css


下一篇:html