- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to 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
- Related Articles
- How to decode JSON objects in Laravel and apply for each loop on that?
- How we can convert Python objects into JSON objects?
- How to Encode and Decode JSON and Lua Programming?
- How can we decode a JSON object in Java?
- How to parse JSON files in Golang?
- How to access nested json objects in JavaScript?
- How to parse JSON Objects on Android?
- How to convert JSON string to array of JSON objects using JavaScript?
- How to parse JSON Objects on Android using Kotlin?
- How to convert pandas DataFrame into JSON in Python?
- How can we merge two JSON objects in Java?
- How to print Python dictionary into JSON format?
- How to deserialize a JSON into Javascript object?
- How to convert JSON string into Lua table?
- How can we write JSON objects to a file in Java?\n
