有没有一种动态解析 JSON 文件的方法,使用 GO 语言。

huangapple go评论113阅读模式
英文:

Is there any way to parse json file dynamically GO

问题

我有一个json文件,但我不知道这个json文件的内容和格式是什么。它可以随时改变。

所以我不能创建一个结构体并根据这个结构体解析它。

有没有一种方法可以动态解析这个json文件并访问其中的值?

我找不到任何相关的信息,如果你有任何帮助,我愿意接受。

英文:

I have a json file, but I don't know what the content and format of this json file is. It can change instantly.

So I cannot create a struct and parse it according to this struct.

Is there a way to dynamically parse this json file and access the values in this json?

I couldn't find anything, if you have any help I'm open to it.

答案1

得分: 1

是的,你可以使用内置的encoding/json包和接口类型在Go中动态解析JSON文件。这是一个示例:

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. )
  7. func main() {
  8. // 将JSON文件读入内存
  9. file, err := ioutil.ReadFile("file.json")
  10. if err != nil {
  11. fmt.Println(err)
  12. return
  13. }
  14. // 将JSON解析为动态接口
  15. var data interface{}
  16. err = json.Unmarshal(file, &data)
  17. if err != nil {
  18. fmt.Println(err)
  19. return
  20. }
  21. // 使用类型断言访问值
  22. m := data.(map[string]interface{})
  23. for k, v := range m {
  24. fmt.Println(k, v)
  25. }
  26. }

在这个示例中,使用json.Unmarshal函数将JSON文件解析为interface{}类型,这是Go中的动态类型,可以保存任何值。然后可以使用类型断言来将动态类型转换为更具体的类型,比如map[string]interface{}

这符合你的需求吗?

英文:

Yes, you can parse a JSON file dynamically in Go by using the built-in encoding/json package and an interface type. Here's an example:

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. )
  7. func main() {
  8. // Read the JSON file into memory
  9. file, err := ioutil.ReadFile("file.json")
  10. if err != nil {
  11. fmt.Println(err)
  12. return
  13. }
  14. // Unmarshal the JSON into a dynamic interface
  15. var data interface{}
  16. err = json.Unmarshal(file, &data)
  17. if err != nil {
  18. fmt.Println(err)
  19. return
  20. }
  21. // Access the values using type assertions
  22. m := data.(map[string]interface{})
  23. for k, v := range m {
  24. fmt.Println(k, v)
  25. }
  26. }

In this example, the json.Unmarshal function is used to parse the JSON file into an interface{} type, which is a dynamic type in Go that can hold any value. The values in the JSON can then be accessed using type assertions to convert the dynamic type to a more specific type, such as map[string]interface{}.

Is this what you mean?

huangapple
  • 本文由 发表于 2023年1月31日 01:06:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75287779.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定