登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-09 10:24:35 205浏览 收藏

有志者,事竟成!如果你在学习Golang,那么本文《我们如何使用 Go 编程语言读取 JSON 文件?》,就很适合你!文章讲解的知识点主要包括,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我正在我的 angular 应用程序上开发一个翻译项目。我已经为此创建了所有不同的密钥。我现在尝试使用 go 编程语言在我的翻译中添加一些功能,以便之后可以快速工作。

我尝试用 go 编程语言编写一个函数,以便读取命令行上的用户输入。我需要读取这个输入文件才能知道里面是否缺少密钥。此输入用户必须是 json 文件。我对这个函数有一个问题,被阻止在 functions.check(err),为了调试我的函数,我用 fmt.printf(要显示的变量) 显示了不同的变量。 我在主函数中将此函数称为 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 runmis-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接口中,然后使用go反射库(https://golang.org/pkg/reflect/)迭代字段,找到它们的名称和值并根据您的需要更新它们。

另一种方法是解组为 map[string]string,但这不能很好地处理嵌套 json,而这可能(但我还没有测试过)。

今天关于《我们如何使用 Go 编程语言读取 JSON 文件?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>