为TOML文件和golang解析表中的键值对

时间:2018-12-24 16:12:37

标签: go toml

我对TOML文件具有以下结构:

[database]
host = "localhost"
port = 8086
https = true
username = "root"
password = "root"
db = "test"

[cloud]
deviceType = "2be386e9bbae"
deviceId = "119a705fa3b1"
password = "test"
token = "dqpx5vNLLTR34"
endpoint = "mqtts://mqtt1.endpoint.com"

[gps]
#measurement = "gps"
  [gps.msgpack]
  topic = "/evt/gps/msgpack"

  [gps.json]
  topic = "/evt/gps/json"

[imu]
#measurement = "imu"
  [imu.1]
    tag = "NODE1"
    topic = "/evt/imu1/msgpack"
  [imu.2]
    tag = "NODE2"
    topic = "/evt/imu2/msgpack"

我只想在measurement表和gps表中设置imu键一次,而不能在msgpackjson中为{{1} }和1

使用注释键,以下代码有效

代码

2

但是在取消注释键值对时,我得到以下信息:

package main

import (
  "fmt"
  "github.com/BurntSushi/toml"
)

type imu struct {
  Topic string
  Measurement string
  Tag string
}

type gps struct {
  // Measurement string
  Measurement string
  ETopic string `toml:"topic"`
}

type database struct {
  Host  string
  Port  int
  Https bool
  Username  string
  Password  string
  Dbname  string
}

type cloud struct {
  Devicetype  string
  DeviceId  string
  Password  string
  Token   string
  Endpoint  string
}

type tomlConfig struct {
  DB database `toml:"database"`
  Cloud cloud `toml:"cloud"`
  Gps map[string]gps `toml:"gps"`
  Imu map[string]imu  `toml:"imu"`
}


func main()  {

  var config tomlConfig

  if _, err := toml.DecodeFile("cloud.toml", &config); err != nil {
    fmt.Println(err)
    return
  }
  // fmt.Printf("%#v\n", config)
  for sensorName, sensor := range config.Imu {
    fmt.Printf("Topic: %s %s %s %s\n", sensorName, sensor.Topic, sensor.Tag, sensor.Measurement)
  }

  for types, gps := range config.Gps {
    fmt.Printf("%s\n", types)
    fmt.Printf("%s\n", gps.ETopic)
  }
}

(它应该仍然是有效的TOML,因为我将其翻译为JSON并检查了结构)

我知道在 toml: type mismatch for main.gps: expected table but found string 中我没有提到需要为其添加字符串。但是,我对结构现在的外观感到困惑。

1 个答案:

答案 0 :(得分:2)

您说:

  

我想在gps表中设置测量键,并且只能将其一次输入,而不能在msgpack和json以及1和2中重复使用

您之所以不会这样做,是因为TOML格式的创建者说:

  

因为我们需要一种体面的人类可读格式,该格式应明确映射到哈希表,并且YAML规范的长度大约为80页,这给我带来了麻烦。不,JSON不计算在内。你知道为什么。

如果您需要一个键具有相同的值,例如measurement,则必须在每个子表中指定所需的值

您正确的TOML文件:

[database]
host = "localhost"
port = 8086
https = true
username = "root"
password = "root"
db = "test"

[cloud]
deviceType = "2be386e9bbae"
deviceId = "119a705fa3b1"
password = "test"
token = "dqpx5vNLLTR34"
endpoint = "mqtts://mqtt1.endpoint.com"

[gps]
[gps.msgpack]
topic = "/evt/gps/msgpack"
measurement = "gps"

[gps.json]
topic = "/evt/gps/json"
measurement = "gps"

[imu]
[imu.1]
measurement = "imu"
tag = "NODE1"
topic = "/evt/imu1/msgpack"
[imu.2]
measurement = "imu"
tag = "NODE2"
topic = "/evt/imu2/msgpack"
相关问题