我们如何使用GO编程语言读取JSON文件



我正在从Angular应用程序上进行翻译项目。我已经为此创建了所有不同的键。我现在尝试使用GO编程语言在翻译中添加一些功能,以快速工作。

我尝试在GO编程语言中编码一个函数,以便在命令行上读取输入用户。我需要阅读此输入文件,以了解内部是否缺少密钥。此输入用户必须是JSON文件。我对此功能有问题,在functions.Check(err)处被阻止,以调试我的功能,我用fmt.Printf(variable to display)显示了不同的变量。我在我的主要功能中称此功能readInput()

readInput()函数如下:

    // this function is used to read the user's input on the command line
func readInput() string {
    // we create a reader
    reader := bufio.NewReader(os.Stdin)
    // we read the user's input
    answer, err := reader.ReadString('n')
    // we check if any errors have occured while reading
    functions.Check(err)
    // we trim the "n" from the answer to only keep the string input by the user
    answer = strings.Trim(answer, "n")
    return answer
}

在我的主函数中,我称readInput()是我创建的特定命令。此命令行可用于更新JSON文件并自动添加丢失的密钥。

我的func main是:

      func main() { 
        if os.Args[1] == "update-json-from-json" {
    fmt.Printf("please enter the name of the json file that will be used to 
    update the json file:") 
    jsonFile := readInput()
    fmt.Printf("please enter the ISO code of the locale for which you want to update the json file: ")
            // we read the user's input
            locale := readInput()
            // we launch the script
            scripts.AddMissingKeysToJsonFromJson(jsonFile, locale)
        }

我可以给您我用于此代码go run mis-t.go update-json-from-json

的命令行

您是否在代码中缺少什么?

假定文件包含动态且未知的键和值,并且您无法在应用程序中对它们进行建模。然后,您可以做类似的事情:


func main() {
    if os.Args[1] == "update-json-from-json" {
        ...
        jsonFile := readInput()
        var jsonKeys interface{}
        err := json.Unmarshal(jsonFile, &jsonKeys)
        functions.Check(err)

        ...
    }
}

将内容加载到empty interface中,然后使用GO反射库(https://golang.org/pkg/reflect/)在字段上迭代,找到他们的姓名和价值,并根据您的需求进行更新。

替代方法是将map[string]string分开,但是与Nested JSON相适应,而这可能会(但我没有测试过)。

最新更新