I'm trying to get this JSON file info into a multidimensional string var in GO:
{
"info": [
{
"type": "general",
"news": [
{ "name": "abc", "read": true },
{ "name": "def", "read": true }
]
},
{
"type": "confidential",
"news": [
{ "name": "xxx", "read": false },
{ "name": "yyy", "read": false }
]
}
]
}
And this is the function used to extract the JSON information
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"`
}
jsonFile, err := os.Open(file_name)
if err != nil {
fmt.Println(err)
}
fmt.Println("Successfully Opened file_name.json")
defer jsonFile.Close()
byteValue, _ := ioutil.ReadAll(jsonFile)
var infor Information
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
}
I'm not sure if this is the best way to extract the JSON information as I have different "types" and looks like I cannot append like that as I'm getting an error regarding the type of variable i'm trying to append.
I'm trying to get this info into the getInfo var which I will return:
getInfo = [general][abc, true, def, true]
[confidential][xxx, false, yyy, false]
Also, I was thinking about return directly infor and extract the information like this in the main function:
func main
.
.
.
info := ReadFile(file_name)
for i, getName := range info.Information.News {
name := getName.Information.News[i].Name
}
.
.
.
CodePudding user response:
type Information struct {
Info []Info `json:"info"`
}
type Info struct {
Type string `json:"type"`
News []New `json:"news"` // Here should be a slice define.
}
type New struct {
Name string `json:"name"`
Read bool `json:"read"`
}
func ReadFile(file_name string) *Information {
jsonFile, err := os.Open(file_name)
if err != nil {
fmt.Println(err)
}
fmt.Println("Successfully Opened file_name.json")
defer jsonFile.Close()
byteValue, _ := ioutil.ReadAll(jsonFile)
var infor Information
json.Unmarshal(byteValue, &infor)
return &infor
}
func main() {
data := ReadFile("./data.json")
for _, news := range data.Info {
for _, v := range news.News {
name := v.Name
// Add you want to do
fmt.Println(name)
}
}
}
You can not get like this:
getInfo = [general][abc, true, def, true]
[confidential][xxx, false, yyy, false]