go - gopkg.in/ini.v1 无法处理同一部分中的重复键
问题描述
使用这样的代码:
package main
import (
"fmt"
"os"
"gopkg.in/ini.v1"
)
func main() {
cfg, err := ini.LoadSources(ini.LoadOptions{AllowShadows: true}, "test.ini")
if err != nil {
fmt.Printf("Fail to read file: %v", err)
os.Exit(1)
}
for _, section := range cfg.Sections() {
for _, key := range section.Keys() {
fmt.Printf("section[%s], key=[%s], value=[%s]\n", section.Name(), key.Name(), key.Value())
}
}
}
使用这样的 INI 文件:
[test]
Key1=Key1Value1
Key1=Key1Value2
Key2=Key2Value1
Key2=Key2Value2
我得到这个输出:
section[test], key=[Key1], value=[Key1Value1]
section[test], key=[Key2], value=[Key2Value1]
我想得到这个输出:
section[test], key=[Key1], value=[Key1Value1]
section[test], key=[Key1], value=[Key1Value2]
section[test], key=[Key2], value=[Key2Value1]
section[test], key=[Key2], value=[Key2Value2]
(不,我无法更改 INI 文件格式,因为我试图复制从另一种语言翻译的行为)
解决方案
你应该使用Key.ValueWithShadows吗?
例如,此修改后的代码将为您提供所需的输出test.ini
:
func main() {
cfg, err := ini.LoadSources(ini.LoadOptions{AllowShadows: true}, "test.ini")
if err != nil {
fmt.Printf("Fail to read file: %v", err)
os.Exit(1)
}
for _, section := range cfg.Sections() {
for _, key := range section.Keys() {
for _, v := range key.ValueWithShadows() {
fmt.Printf("section[%s], key=[%s], value=[%s]\n", section.Name(), key.Name(), v)
}
}
}
}
推荐阅读
- python - 不明白为什么我得到一个变量的 NameError
- go - Golang检查不存在的路径是否是目录
- html - 变量 JSP 没有在 HTML 中获取输入文本值
- ruby - 将哈希值乘以一个数字,对于负值返回 0
- firebase - 无法在flutter中使用StreamBuilder访问firebase中的数据
- sql - 使用 group by 对同一列中的某些值进行多次计数
- javascript - 添加firebase firestore对象反应本机
- node.js - 每次重试都超时重试 Axios POST 请求
- python - Python Pandas - CSV 导入 RFC 4180
- javascript - React 是 setstate 弄乱了我的算法吗?