C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Main: Here we create an instance of our Box type. We specify its Width, Height, Color and its Open value.
Json.Marshal: This receives an object instance. We pass it our Box instance and it converts it to a byte slice of the encoded data.
Result: We convert our bytes (b) to a string and display them with fmt.Println.
ConvertGolang program that converts object to JSON encoding
package main
import (
"encoding/json"
"fmt"
)
type Box struct {
Width int
Height int
Color string
Open bool
}
func main() {
// Create an instance of the Box struct.
box := Box{
Width: 10,
Height: 20,
Color: "blue",
Open: false,
}
// Create JSON from the instance data.
// ... Ignore errors.
b, _ := json.Marshal(box)
// Convert bytes to string.
s := string(b)
fmt.Println(s)
}
Output
{"Width":10,"Height":20,"Color":"blue","Open":false}
Text: We specify a JSON string as text. We then convert it to a byte slice with a conversion.
BytesUnmarshal: We invoke Unmarshal by passing a pointer to an empty array of structs. The Languages slice is empty, but Unmarshal populates it.
Finally: We loop over the structs that were created by Unmarshal(). We display their Id and Name fields.
Golang program that uses json.Unmarshal
package main
import (
"encoding/json"
"fmt"
)
type Language struct {
Id int
Name string
}
func main() {
// String contains two JSON rows.
text := "[{\"Id\": 100, \"Name\": \"Go\"}, {\"Id\": 200, \"Name\": \"Java\"}]"
// Get byte slice from string.
bytes := []byte(text)
// Unmarshal string into structs.
var languages []Language
json.Unmarshal(bytes, &languages)
// Loop over structs and display them.
for l := range languages {
fmt.Printf("Id = %v, Name = %v", languages[l].Id, languages[l].Name)
fmt.Println()
}
}
Output
Id = 100, Name = Go
Id = 200, Name = Java
Result: This struct contains an int slice with field name Positions. This where the int array values are placed.
Unmarshal: We use this to convert our byte array of JSON data into a single struct. Finally we print values on the Result struct.
Golang program that handles int array in JSON
package main
import (
"encoding/json"
"fmt"
)
type Result struct {
Positions []int
}
func main() {
// This JSON contains an int array.
text := "{\"Positions\": [100, 200, 300, -1]}"
// Get bytes.
bytes := []byte(text)
// Unmarshal JSON to Result struct.
var result Result
json.Unmarshal(bytes, &result)
// Our int array is filled.
fmt.Printf("Positions = %v", result.Positions)
fmt.Println()
// Print int array length.
fmt.Printf("Length = %v", len(result.Positions))
fmt.Println()
}
Output
Positions = [100 200 300 -1]
Length = 4
Quote: Although originally derived from the JavaScript scripting language, JSON is a language-independent data format. Code for parsing and generating JSON data is readily available in many programming languages.
JSON: Wikipedia