
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Decode JSON into Objects in Golang
Suppose we have a JSON that looks like this.
{ "name":"Mukul Latiyan", "age":10, "sports":[ "football", "tennis", "cricket" ] }
Now, we want to convert this JSON into struct fields which we can access later and maybe iterate over too.
In order to do that, we need to first make a struct that will satisfy the fields of the above JSON.
The struct shown below will work just fine for the above JSON.
type Person struct { Name string `json:"name"` Age int `json:"age"` Sports []string `json:"sports"` }
Now, the next step is to convert the above JSON object into a slice of bytes in Go, with the help of type conversion, and then, we will pass that slice of bytes to the Unmarshal() function along with the Person object as the second argument.
Example
Consider the code shown below.
package main import ( "encoding/json" "fmt" ) type Person struct { Name string `json:"name"` Age int `json:"age"` Sports []string `json:"sports"` } func main() { text := []byte( `{ "name":"Mukul Latiyan", "age":10, "sports":["football","tennis","cricket"] }`) var p Person err := json.Unmarshal(text, &p) if err != nil { panic(err) } fmt.Println(p.Name) fmt.Println(p.Age) for _, value := range p.Sports { fmt.Println(value) } }
In the above code, after calling the Unmarshal function, we are simply printing the values of different fields of the struct.
If we run the command go run main.go on the above code, then we will get the following output in the terminal.
Output
Mukul Latiyan 10 football tennis cricket