Golang如何将JSON数据解析到多维字符串变量中

Golang如何将JSON数据解析到多维字符串变量中 我从一个JSON文件中获取以下信息:

{
    "info": [
      {
        "type": "general",
        "news": [
          { "name": "abc",  "read": true },
          { "name": "def",  "read": true }
        ]
      },
      {
        "type": "confidential",
        "news": [
          { "name": "xxx",  "read": false },
          { "name": "yyy",  "read": false }
        ]
      }
    ]
}

这是用于提取JSON信息的函数:

func ReadFile(file_name string) [ ][ ]string {

	var getInfo [ ][ ]string

	type News struct {
		Name    string  `json:"name"`
		Read     bool    `json:"read"`
	}

	type Info struct {
		Type  string  `json:"type"`
		News News `json:"news"`
	}

	type Information struct {
		Info  [ ]Info `json:"info"`
	}

	// Open file
	jsonFile, err := os.Open(file_name)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println("Successfully Opened file_name.json")
	// defer the closing of our jsonFile so that we can parse it later on
	defer jsonFile.Close()

	// read our opened file_name as a byte array.
	byteValue, _ := ioutil.ReadAll(jsonFile)

	var infor Information

	// we unmarshal our byteArray which contains our
	// jsonFile's content into 'Infor' which we defined above
	json.Unmarshal(byteValue, &infor)

	for i := 0; i < len(infor.Information); i++ {
		getInfo[i] = append(getInfo[i], infor.Information[i].Type)
		for j := 0; j < len(infor.Information.News); j++ {
			getInfo[i][j] = append(getInfo, infor.Information[i].News[j].Name)
			getInfo[i][j+1] = append(getInfo, infor.Information[i].News[j].Read)
		}
	}
	return getInfo
}

我不确定这是否是提取JSON信息的最佳方式,因为我有不同的“类型”,而且看起来我不能像那样进行追加操作,因为我遇到了关于要追加的变量类型的错误。

基本上,我试图将这些信息放入getInfo变量中:

getInfo = [general][abc, true, def, true]
          [confidential][xxx, false, yyy, false]

更多关于Golang如何将JSON数据解析到多维字符串变量中的实战教程也可以访问 https://www.itying.com/category-94-b0.html

6 回复

请再次查看。我已编辑了消息。

更多关于Golang如何将JSON数据解析到多维字符串变量中的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


问题已经解决了。我必须在主函数外部声明结构体。

你没有提到具体的问题。你的代码在我这里可以编译,所以这一定是一个运行时错误。我猜测这是由于你忽略了错误处理导致的。

  1. 你可以轻松地将你的 JSON 反序列化到一个 []Info 中。

    X_T: 2. 这个

    getInfo = [general][abc, true, def, true]
              [confidential][xxx, false, yyy, false]
    

    并不是一个 [][]string 应有的样子。如果你确实想要一个 [][]string,也许你的意思是让它看起来像这样: [["general","abc, true, def, true"], ["confidential","xxx, false, yyy, false"]

  2. 我建议你按照第 1 点的方法进行反序列化,然后将 []Info 转换为你想要的类型。

感谢您的回答。

最终我尝试了类似下面的做法,但它在 ReadFile 函数中报错,提示“Environments”未声明。

我在 main 函数中声明了 Environments 结构体,并在调用 ReadFile 函数时仅将文件名作为参数传递:

func main () {

type Information struct {
    Info []Info `json:"info"`
}

type Info struct {
    Type string `json:"type"`
    News []New  `json:"news"` 
}

type New struct {
    Name string `json:"name"`
    Read bool   `json:"read"`
}

file_name := "file.json"
reading := ReadFile(file_name)

这是 ReadFile 函数:

func ReadFile(file_name string) *Information {
    jsonFile, err := os.Open(file_name)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println("Successfully Opened file.json")

    defer jsonFile.Close()

    byteValue, _ := ioutil.ReadAll(jsonFile)

    var infor Information

    json.Unmarshal(byteValue, &infor)

    return &infor
}

我不确定这是否是一个运行时错误。

在Go语言中解析JSON到多维字符串变量时,需要正确定义结构体来匹配JSON的嵌套数组结构。以下是修正后的代码:

package main

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

func ReadFile(fileName string) [][]string {
    type NewsItem struct {
        Name string `json:"name"`
        Read bool   `json:"read"`
    }

    type InfoItem struct {
        Type  string     `json:"type"`
        News []NewsItem `json:"news"`
    }

    type Information struct {
        Info []InfoItem `json:"info"`
    }

    // 打开文件
    jsonFile, err := os.Open(fileName)
    if err != nil {
        fmt.Println(err)
        return nil
    }
    defer jsonFile.Close()

    // 读取文件内容
    byteValue, err := ioutil.ReadAll(jsonFile)
    if err != nil {
        fmt.Println(err)
        return nil
    }

    // 解析JSON
    var infoData Information
    err = json.Unmarshal(byteValue, &infoData)
    if err != nil {
        fmt.Println(err)
        return nil
    }

    // 创建结果切片
    var getInfo [][]string
    
    for _, info := range infoData.Info {
        var row []string
        row = append(row, info.Type)
        
        for _, news := range info.News {
            row = append(row, news.Name)
            row = append(row, fmt.Sprintf("%v", news.Read))
        }
        
        getInfo = append(getInfo, row)
    }
    
    return getInfo
}

func main() {
    result := ReadFile("data.json")
    fmt.Printf("%v\n", result)
}

输出结果:

[[general abc true def true] [confidential xxx false yyy false]]

如果需要保持每个新闻项的name和read作为单独的子切片,可以使用以下变体:

func ReadFile(fileName string) [][]string {
    // ... 结构体定义和文件读取部分与上面相同 ...

    var getInfo [][]string
    
    for _, info := range infoData.Info {
        var row []string
        row = append(row, info.Type)
        
        for _, news := range info.News {
            row = append(row, news.Name, fmt.Sprintf("%v", news.Read))
        }
        
        getInfo = append(getInfo, row)
    }
    
    return getInfo
}

或者如果需要三层嵌套结构:

func ReadFile(fileName string) [][][]string {
    // ... 结构体定义和文件读取部分与上面相同 ...

    var getInfo [][][]string
    
    for _, info := range infoData.Info {
        var typeGroup [][]string
        
        for _, news := range info.News {
            newsItem := []string{news.Name, fmt.Sprintf("%v", news.Read)}
            typeGroup = append(typeGroup, newsItem)
        }
        
        getInfo = append(getInfo, typeGroup)
    }
    
    return getInfo
}
回到顶部