golang yaml与json配置文件互

栏目: Go · 发布时间: 7年前

  • java 中可利用snakeyaml库进行yaml与json配置文件格式互转,原理就是yaml解析为map对象,再将ma对象p转为json,反之亦然
  • 本文重点介绍yaml文件的解析
  • golang中比较流行的yaml.v2提供了对yaml配置文件的操作,encoding/json库提供了对json配置文件的操作,但比较繁琐的是可能需要在代码中定义对应配置文件结构的struct结构来存储解析结构,缺少灵活度。但也可以利用Unmarshal、marshal来直接解析成map存储。
  • 将yaml配置内容解析到map对象中
package main

import (
    "fmt"
    "log"

    "gopkg.in/yaml.v2"
    "io/ioutil"
)


func main() {
    t := map[string]interface{}{}
    buffer, err := ioutil.ReadFile("./config.dev.yaml")
    err = yaml.Unmarshal(buffer, &t)
    if err != nil {
        log.Fatalf(err.Error())
    }
    fmt.Printf("%v",t)
}
  • 理论上可以利用yaml.v2将yaml转为map,再将map转为json,但是golang的类型转换实在恶心...
  • yaml配置文件转json格式。这里需要另一个库 https://github.com/ghodss/yaml
# 安装
go get -u github.com/ghodss/yaml
# 使用
package main

import (
    "fmt"

    "github.com/ghodss/yaml"
)

func main() {
    j := []byte(`{"name": "John", "age": 30}`)
    y, err := yaml.JSONToYAML(j)
    if err != nil {
        fmt.Printf("err: %v\n", err)
        return
    }
    fmt.Println(string(y))
    /* Output:
    name: John
    age: 30
    */
    j2, err := yaml.YAMLToJSON(y)
    if err != nil {
        fmt.Printf("err: %v\n", err)
        return
    }
    fmt.Println(string(j2))
    /* Output:
    {"age":30,"name":"John"}
    */
}
  • 在实战中,是先调用yaml.YAMLToJSON将yaml转为json文本,再利用json.Unmarshal将json文本解析为内存map。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

We Are the Nerds

We Are the Nerds

Christine Lagorio-Chafkin / Hachette Books / 2018-10-2 / USD 18.30

Reddit hails itself as "the front page of the Internet." It's the third most-visited website in the United States--and yet, millions of Americans have no idea what it is. We Are the Nerds is an eng......一起来看看 《We Are the Nerds》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具