首页 > 解决方案 > 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 文件格式,因为我试图复制从另一种语言翻译的行为)

标签: go

解决方案


你应该使用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)
            }
        }
    }
}

推荐阅读