JSON in Go: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
Line 1: Line 1:
=Internal=
=Internal=
* [[Go Code Examples#Code_Examples|Go Code Examples]]
* [[Go Code Examples#Code_Examples|Go Code Examples]]
* [[Go Package json]]
* [[Go Package encoding/json]]
* [[JSON#Subjects|JSON]]
* [[JSON#Subjects|JSON]]



Revision as of 21:27, 25 August 2023

Internal

Overview

JSON Marshalling Go → JSON

JSON marshalling means generating a JSON representation from a Go object. It is done with json.Marshal(). The result is a byte array. To convert the byte array to a string, see:

Go Integers | Conversion between bytes and strings

Map Marshalling

Struct Marshalling

By default, only fields that start with capital letters are marshaled. The fields that start with lower caps are invisible to the marshaling process.

type Item struct {
  Color string
  Size int
  Options []string
}

i := Item{Color: "blue", Size: 5, Options: []string{"brake", "acceleration", "lights"}}

ba, err := json.Marshal(i) // pass the value

fmt.Println(string(ba))

JSON Unmarshalling JSON → Go

Unmarshalling into Struct

type Item struct {
  Color string
  Size int
  Options []string
}

s := "{\"Color\":\"blue\",\"Size\":5,\"Options\":[\"brake\",\"acceleration\",\"lights\"]}"
ba := []byte(s)
var i Item

err := json.Unmarshal(ba, &i) // pass the pointer

fmt.Printf("%+v\n", i)

TO PROCESS

TO PROCESS: https://golang.cafe/blog/golang-json-marshal-example.html