将JSON文件解析为Golang中的结构体。

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

Parsing JSON file into struct golang

问题

我有一个JSON文件:

{
"AHSS": {
"终身学习": "1sVhClGzmD5N_S6wGiS9_xHj2IkVgSv_un0rktvH2Goo",
"测试学习": "1sdfVhClGzmD5N_S6wGiS9_xHj2ffgIkVgSv_un0rko56545o",
"测试学习2": "fg1ac_PiSaWzeL3bA3tjWYs23dh61sVhClHj2IkVgSv_un0rktvH2Goo",
"测试学习3": "13444sVhClGzmD5N_S6wGiS9_xHj2IkVgSv_un0rktyutvH2Goo",
"测试学习4": "6657681sVhClGzmD5N_S6wGiS9_xHj2IkVgSv_un0rktvH2Goo"
},
"ProfServices": {
"IT": "1fgac_PiSaWzeLxxdVuZs3bA3tjWY345d",
"SomethingElse": "1ac_Pi3bA3tjWY4563",
"Foo": "12ac_PiVuZs3bA3tjWYghfgj",
"Bar": "445341ac_PiSaWzeLxA3tjWY54",
"School1": "fg1ac_PiSaWzeL3bA3tjWYs23dh6",
"School2": "fg341ac_PiSaWzeLZs3bA3tjWYsd4",
"School3": "fgdf1ac_PiSaWzeLuZs3bA3tjWdgfY"
},
"CollegeOfEngineering": {
"数学": "asdasdasdas45",
"物理": "pa6asa_Asddg",
"天体物理学": "asdfdasdasda",
"School5": "mykeyyslaksdlkasmdlka",
"School6": "asdasdkeykeykeykey"
},
"AnotherCollege": {
"School7": "f111g1a2c_PiSaWzeL3bA3tjWYsdh6",
"School8": "f4434234g341ac_PiSafgdfgdfgWzeLZs3bA3tjWYsd4",
"School9": "fg23df1ac_PiSaWzeLuZs3bA3tjWdgfY"
}
}

这只是一个用于测试的示例,但我的实际JSON文件将包含更多数据。但格式始终相同。我将有一个'Colleges'的数组,例如'AHSS'和'ProfServices'。在这些学院中有'学校',例如'IT'或'终身学习'。每个学校都有自己独特的键。我需要读取此JSON文件并将其转换为结构体。

我尝试过使用json.Decode和json.Unmarshal,并且我真的不知道如何获得我所需的内容。我尝试的所有方法都打印出一个空的结构体。也许我的go语言结构体布局有问题?

这是我使用的结构体布局(不确定是否正确):

// Sheets结构体将从sheets.json导入
Sheets struct {
Colleges []struct {
SheetKeys []string
}
}
)

这是我尝试使用的两种方法,以实现将json文件导入结构体的目标。

1)

sheetData,err:= os.Open(“sheets.json”)
if err!= nil {
log.Fatalln(err)
}

jsonParser:= json.NewDecoder(sheetData)
s:= Sheets {}
jsonParser.Decode(& s)
log.Println(s)

2)

sheetData,err:= ioutil.ReadFile(“sheets.json”)
s:= Sheets {}
err = json.Unmarshal(sheetData,& s)
if err!= nil {
log.Fatalln(err)
}

log.Println(s)

有人可以提供正确导入此json文件的方法吗?我不确定是我做的方法有问题,还是结构体布局有问题。

谢谢。

英文:

I have this JSON file:

    {
  "AHSS": {
    "Lifelong Learning": "1sVhClGzmD5N_S6wGiS9_xHj2IkVgSv_un0rktvH2Goo",
    "TEST Learning": "1sdfVhClGzmD5N_S6wGiS9_xHj2ffgIkVgSv_un0rko56545o",
    "TEST Learning2": "fg1ac_PiSaWzeL3bA3tjWYs23dh61sVhClHj2IkVgSv_un0rktvH2Goo",
    "TEST Learning3": "13444sVhClGzmD5N_S6wGiS9_xHj2IkVgSv_un0rktyutvH2Goo",
    "TEST Learning4": "6657681sVhClGzmD5N_S6wGiS9_xHj2IkVgSv_un0rktvH2Goo"
  },
  "ProfServices": {
    "IT": "1fgac_PiSaWzeLxxdVuZs3bA3tjWY345d",
    "SomethingElse": "1ac_Pi3bA3tjWY4563",
    "Foo": "12ac_PiVuZs3bA3tjWYghfgj",
    "Bar": "445341ac_PiSaWzeLxA3tjWY54",
    "School1": "fg1ac_PiSaWzeL3bA3tjWYs23dh6",
    "School2": "fg341ac_PiSaWzeLZs3bA3tjWYsd4",
    "School3": "fgdf1ac_PiSaWzeLuZs3bA3tjWdgfY"    
  },
  "CollegeOfEngineering": {
    "Maths": "asdasdasdas45",
    "Physics": "pa6asa_Asddg",
    "Astrophysics": "asdfdasdasda",
    "School5": "mykeyyslaksdlkasmdlka",
    "School6": "asdasdkeykeykeykey"
  },
  "AnotherCollege": {
    "School7": "f111g1a2c_PiSaWzeL3bA3tjWYsdh6",
    "School8": "f4434234g341ac_PiSafgdfgdfgWzeLZs3bA3tjWYsd4",
    "School9": "fg23df1ac_PiSaWzeLuZs3bA3tjWdgfY"
  }
}

This is just an example to test with, but my actual json file will have a lot more data. But the format will always be the same. I will have an array of 'Colleges' such as 'AHSS' and ProfServices'. Within these Colleges are 'Schools' such as 'IT' or ' Lifeling Learning'. Each school has its own unique key. I need to read this JSON file and convert it into a struct.

I've tried looking around and using both json.Decode and json.Unmarshal and I'm really not sure how to get what I need. Everything I've tried prints out an empty struct. Maybe the layout of my struct in go is wrong?

Here is the struct layout I am using (not 100% this is correct):

	// Sheets struct will import from sheets.json
	Sheets struct {
		Colleges []struct {
			SheetKeys []string
		}
	}
)

And here are two methods I tried using to achieve my goal of importing the json file into a struct.

1)

sheetData, err := os.Open("sheets.json")
if err != nil {
	log.Fatalln(err)
}

jsonParser := json.NewDecoder(sheetData)
s := Sheets{}
jsonParser.Decode(&s)
log.Println(s)

2)

sheetData, err := ioutil.ReadFile("sheets.json")
s := Sheets{}
err = json.Unmarshal(sheetData, &s)
if err != nil {
	log.Fatalln(err)
}

log.Println(s)

Can anybody provide a method of importing this json file correctly? I'm not sure if its a problem with my method of doing it, or if its a problem with the struct layout.

Thanks.

答案1

得分: 1

你有一个包含字符串对象的对象。这个对象最自然地解组成了

map[string]map[string]string

然后,你可以像处理其他任何map一样使用它。

Playground: http://play.golang.org/p/_IX8WUDn4b.

英文:

You have an object of objects of strings. This unmarshals most naturally into

map[string]map[string]string

Then just work with it as you would with any other map.

Playground: http://play.golang.org/p/_IX8WUDn4b.

答案2

得分: 0

这是我写的将JSON字符串转换为结构体或将结构体转换为JSON的代码。只需将您的结构体(类似于您的JSON)作为interface{}传递。

/*
JSONStringToStructure 错误
将JSON字符串转换为给定的结构体
*/
func JSONStringToStructure(jsonString string, structure interface{}) error {
    jsonBytes := []byte(jsonString)
    return json.Unmarshal(jsonBytes, structure)
}

/*
StructureToJSON (string,error)
将结构体转换为JSON字符串
*/
func StructureToJSON(structure interface{}) (string, error) {
    bin, err := json.Marshal(structure)
    return string(bin), err
}

希望对您有所帮助!

英文:

this is what i wrote to convert JSON string to struct or struct To JSON.
just pass your struct ( like your JSON ) as interface{}

/*
JSONStringToStructure error
convert json string to given struct
*/
func JSONStringToStructure(jsonString string, structure interface{}) error {
	jsonBytes := []byte(jsonString)
	return json.Unmarshal(jsonBytes, structure)
}

/*
StructureToJSON (string,error)
convert struct to json string
*/
func StructureToJSON(structure interface{}) (string, error) {
	bin, err := json.Marshal(structure)
	return string(bin), err
}

huangapple
  • 本文由 发表于 2015年7月24日 17:41:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/31607205.html
匿名

发表评论

匿名网友

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

确定