Home » Go JSON

Go JSON

Go has built-in support for JSON encoding and decoding. it also supports custom datatypes.

The Marshal function is used to convert go data types into JSON format.

Marshal function syntax is:

Marshal returns the JSON encoding of v.

Boolean is converted to JSON booleans. Floating point, integer, and Number are converted to JSON numbers. The map’s key type must either be a string, an integer type, or implement encoding.TextMarshaler.

The decoding of JSON is done using Unmarshal function.

Unmarshal function syntax is:

Unmarshal decodes JSON-encoded value and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an InvalidUnmarshalError.

We can also customize the fields stored under the “json” key in the struct field’s tag. we can have name of the field, followed by a comma-separated list of options. Like

Go JSON Example 1

Output:

false 10 3.14 "tutoraspire" ["sun","moon","star"] {"moon":2,"sun":1} 

Go JSON Example 2 (User Defined Data Type)

Output:

{"Position":1,"Planet":["mercury","venus","earth"]} {"position":1,"planet":["mercury","venus","earth"]} map[pi:6.13 place:[New York New Delhi]] 6.13 New York {1 [mercury venus]} venus {"1":"mercury","2":"venus"} 

You may also like