duanlie3187 2018-05-10 15:42
浏览 165

在Go中加载动态yaml结构[关闭]

I'm trying to convert some Python code to Golang, and I'm having some difficulty figuring out how to load dynamic yaml data, which I thought was pretty basic. So far, all of the approaches I have found mention creating a Struct and mapping values, but this won't be possible since the data I'll be receiving will be different every time it's read.

This isn't the real data (which will actually be returned from an API), but as an example yaml file:

[ ~]$ cat /tmp/example.yaml
Massachusetts:
  cities:
    - name: 'Boston'
      area_code: 617
    - name: 'Springfield'
    - name: 'Worcester'
Virginia:
  cities:
    - name: 'Richmond'
    - name: 'Arlington'
      landmarks:
        - 'The Pentagon'
        - 'National Airport'
        - 'Arlington National Cemetary'
  presidents:
    - 'George Washington'
    - 'Thomas Jefferson'
    - 'James Madison'
    - 'James Monroe'
    - 'William Henry Harrison'
    - 'John Tyler'
Missouri:
  rivers:
    - 'Missouri River'
    - 'Mississippi'
    - 'Arkansas River'
    - 'White River'

And reading and manipulating it in Python is simple:

#!/usr/bin/python
import yaml
with open('/tmp/example.yaml', 'r') as fh:
    data = yaml.load(fh)

print yaml.dump(data, default_flow_style=False)

As I'm new to Go, does anyone know which technique I should use / documentation I should look for that will do what this Python code does?

  • 写回答

2条回答 默认 最新

  • douju7765 2018-05-10 17:20
    关注

    One of the most popular go yaml packages has this exact example in their documentation:

    package main
    
    import (
            "fmt"
            "log"
    
            "gopkg.in/yaml.v2"
    )
    
    var data = `
    a: Easy!
    b:
      c: 2
      d: [3, 4]
    `
    
    func main() {
         m := make(map[interface{}]interface{})
    
         err = yaml.Unmarshal([]byte(data), &m)
         if err != nil {
             log.Fatalf("error: %v", err)
         }
         fmt.Printf("--- m:
    %v
    
    ", m)
    }
    

    As Flimzy points out above in his comment, now it is up to your app to dynamically handle the schema. I feel like this may qualify as "Schema on Read" and there are many tradeoffs to this approach vs an approach where you use a static definition of the data:

    • type assertions/inspection must be handled at runtime, after unmarshalling
    • Schema must be codified in logic and assertions instead of declared
    • ??

    I would def question if you truly have dynamic data?

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度