json operation for Golang

Keywords: Programming JSON encoding Go Javascript

  • JavaScript Object Representation (JSON) is a standard Protocol for sending and receiving structured information.JSON is not the only standard Protocol among similar protocols.XML (7.14), ASN.1, and Google's Proocol Buffers are similar protocols and have their own features, but JSON is the most widely used because of its simplicity, readability, popularity, and so on.
  • The Go language has good support for encoding and decoding of these standard formats, supported by packages such as encoding/json, encoding/xml, encoding/asn1 in the standard library, and has similar API interfaces.In this section, we will give an overview of the usage of the important encoding/json packages.
  • JSON is the Unicode text encoding for various types of values in JavaScript -- strings, numbers, Boolean values, and objects.It can represent aggregated data types such as underlying data types and arrays, slice s, structs, and map s in an efficient and readable manner.
  • The basic JSON types are numbers (decimal or scientific notation), Boolean values (true or false), strings, where strings are Unicode character sequences contained in double quotes that support backslash escape similar to the Go language, but JSON uses \Uhhhh escape numbers to represent a UTF-16 encoding (Note:UTF-16, like UTF-8, is a variable-length encoding, with some characters with larger Unicode points requiring four bytes; UTF-16 also has big and small-end problems, rather than the GoLanguage rune type.
  • These basic types can be combined recursively through an array of JSON s and object types.
  • A JSON array is an ordered sequence of values written in square brackets separated by commas; a JSON array can be used to encode arrays and slice s in the Go language.
  • A JSON object is a string-to-value mapping written as a series of name:value pairs, enclosed in curly brackets and separated by commas; JSON object types can be used to encode map types (key types are strings) and structs for the Go language.
// test13_json project main.go
package main

import (
	"encoding/json"
	"fmt"
	"log"
)

type Movie struct {
	Title  string
	Year   int  `json:"released"`
	Color  bool `json:"color,omitempty"`
	Actors []string
}

var movies = []Movie{
	{
		Title:  "Wolf 2",
		Year:   2017,
		Color:  true,
		Actors: []string{"Wu Jing", "Wu Gang"},
	},
	{
		Title:  "Old Gun",
		Year:   2015,
		Color:  true,
		Actors: []string{"Feng Xiaogang", "Kris", "Xu Qing"},
	},
	{
		Title:  "Bullitt",
		Year:   1968,
		Color:  false,
		Actors: []string{"Steve McQueen", "Jacqueline Bisset"},
	},
}

func main() {
	/*
		Note that json codec can only handle struct member variables as uppercase fields, ignoring lowercase directly
		If you want the field of the json string to be lowercase when encoding, you need to add Tag to the recombination structure
		If json has lowercase field names when decoding, then when defining the structure receive, the member names are capitalized, followed by Tag
	*/
	
	//Encoding, converting go structure to json string
	//json_str, err :=json.Marshal(movies)
	json_data, err := json.MarshalIndent(movies, "", "	") // Output format with indentation
	if err != nil {
		log.Fatal(err)
		return
	}
	fmt.Printf("%s\n", json_data)
	fmt.Println("-----------------------------")

	var titles []struct {
		Title string
	}

	if err := json.Unmarshal(json_data, &titles); err != nil {
		log.Fatal(err)
		return
	}
	fmt.Printf("%+v\n", titles)

	var years []struct {
		Year int `json:"released"`
	}
	if err := json.Unmarshal(json_data, &years); err != nil {
		log.Fatal(err)
		return
	}
	fmt.Printf("%+v\n", years)

	var actors []struct {
		Actors []string
	}
	if err := json.Unmarshal(json_data, &actors); err != nil {
		log.Fatal(err)
		return
	}
	fmt.Printf("%+v\n", actors)
	fmt.Println("--------------------------")

	var my_movies []struct {
		Title  string
		Year   int `json:"released"`
		Actors []string
	}

	if err := json.Unmarshal(json_data, &my_movies); err != nil {
		log.Fatal(err)
		return
	}
	fmt.Printf("%+v\n", my_movies)
}

The output is as follows:

[
	{
		"Title": "Wolf 2".
		"released": 2017,
		"color": true,
		"Actors": [
			"Wu Jing",
			"Wu Gang"
		]
	},
	{
		"Title": "Old Gun".
		"released": 2015,
		"color": true,
		"Actors": [
			"Feng Xiaogang",
			"Wu Yifan",
			"Xu Qing"
		]
	},
	{
		"Title": "Bullitt",
		"released": 1968,
		"Actors": [
			"Steve McQueen",
			"Jacqueline Bisset"
		]
	}
]
-----------------------------
[{Title:Wolf 2} {Title:Old Gun} {Title:Bullitt}]
[{Year:2017} {Year:2015} {Year:1968}]
[{Actors:[Wu Jing Wu Gang]} {Actors:[Feng Xiaogang Wu Yi Xu Qing]} {Actors:[Steve McQueen Jacqueline Bisset]}]
--------------------------
[{Title:Wolf 2 Year:2017 Actors:[Wu Jing Wu Gang]} {Title:Gunner Year:2015 Actors:[Feng Xiao Gang Wu Yi Fan Xu Qing]} {Title:Bullitt Year:1968 Actors:[Steve McQueen Jacqueline Bisset]}]
Success: Process exit code 0.

Posted by GregArtemides on Sun, 22 Mar 2020 00:00:01 -0700