为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
白板的微信 2023-06-12 16:16:01
我正在我的 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 linefunc 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请问我的代码中缺少什么吗?
查看完整描述

1 回答

?
开心每一天1111

TA贡献1836条经验 获得超13个赞

假设该文件包含动态和未知的键和值,并且您无法在您的应用程序中对它们进行建模。然后你可以这样做:



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/ ) 遍历字段,找到它们的名称和值并根据您的需要更新它们。


另一种方法是 Unmarshal into a map[string]string,但这不能很好地处理嵌套的 JSON,而这可能(但我还没有测试过)。


查看完整回答
反对 回复 2023-06-12
  • 1 回答
  • 0 关注
  • 101 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信