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

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

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文件。这是一个示例:

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
)

func main() {
	// 将JSON文件读入内存
	file, err := ioutil.ReadFile("file.json")
	if err != nil {
		fmt.Println(err)
		return
	}

	// 将JSON解析为动态接口
	var data interface{}
	err = json.Unmarshal(file, &data)
	if err != nil {
		fmt.Println(err)
		return
	}

	// 使用类型断言访问值
	m := data.(map[string]interface{})
	for k, v := range m {
		fmt.Println(k, v)
	}
}

在这个示例中,使用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:

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
)

func main() {
	// Read the JSON file into memory
	file, err := ioutil.ReadFile("file.json")
	if err != nil {
		fmt.Println(err)
		return
	}

	// Unmarshal the JSON into a dynamic interface
	var data interface{}
	err = json.Unmarshal(file, &data)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Access the values using type assertions
	m := data.(map[string]interface{})
	for k, v := range m {
		fmt.Println(k, v)
	}
}

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:

确定