search
HomeBackend DevelopmentGolangTeach you how to use Json in Go

Teach you how to use Json in Go

Dec 28, 2021 pm 03:44 PM
go language

This article is provided by the golang tutorial column to introduce how to use Json in the Go language. I hope it will be helpful to friends in need!

Encode

Encode an object into JSON data, accepting an interface{} Object, returns []byte and error:

func Marshal(v interface{}) ([]byte, error)

Marshal The function will recursively traverse the entire object and evaluate the object by member type in turn. Encoding, the type conversion rules are as follows:

  • bool type conversion to JSONBoolean

  • Integers, floating point numbers and other numerical types are converted to JSONNumber

  • string Convert to a string of JSON (with "" quotes)

  • struct Convert to a of JSON Object, and then recursively pack the

  • array or slice into JSON’s Array

    ## based on the type of each member.
  • #[]byte will be base64 encoded first and then converted to JSON string

  • map converted to Object converted to JSON, key must be string

  • ##interface{}

    Convert according to the actual internal type

  • ##nil
  • Convert to

    JSONnull

    ##channel
  • ,
  • func

    and other types will return UnsupportedTypeError <pre class="brush:php;toolbar:false">type ColorGroup struct {   ID  int   Name string   Colors []string  } group := ColorGroup{   ID:  1,   Name: &quot;Reds&quot;,   Colors: []string{&quot;Crimson&quot;, &quot;Red&quot;, &quot;Ruby&quot;, &quot;Maroon&quot;}, } b, err := json.Marshal(group) if err != nil {   fmt.Println(&quot;error:&quot;, err) } os.Stdout.Write(b) Output: {&quot;ID&quot;:1,&quot;Name&quot;:&quot;Reds&quot;,&quot;Colors&quot;:[&quot;Crimson&quot;,&quot;Red&quot;,&quot;Ruby&quot;,&quot;Maroon&quot;]}</pre>

Decode

Decode JSONdata

func Unmarshal(data []byte, v interface{}) error

Type conversion rules and the above rules Similar to <pre class="brush:php;toolbar:false">var jsonBlob = []byte(`[   {&quot;Name&quot;: &quot;Platypus&quot;, &quot;Order&quot;: &quot;Monotremata&quot;},   {&quot;Name&quot;: &quot;Quoll&quot;, &quot;Order&quot;: &quot;Dasyuromorphia&quot;}  ]`) type Animal struct {   Name string   Order string  } var animals []Animal  err := json.Unmarshal(jsonBlob, &amp;animals) if err != nil {   fmt.Println(&quot;error:&quot;, err) } fmt.Printf(&quot;%+v&quot;, animals) Output: [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]</pre>

structure

The structure must be a member starting with a capital letter to be processed by JSON, Members starting with a lowercase letter have no effect.

Mashal, the member variable name of the structure will be directly packaged into ## as the

key

of JSON Object #JSONUnmashal, the corresponding variable name will be automatically matched for assignment, and is not case-sensitive. When Unmarshal, if there are extra fields in JSON

, they will be discarded directly; if

JSON is missing a field, it will be discarded directly. Ignore not assigning values ​​to variables in the structure and no error will be reported.

type Message struct { 
 Name string 
 Body string 
 Time int64 
 inner string 
} var m = Message{ 
 Name: "Alice", 
 Body: "Hello", 
 Time: 1294706395881547000, 
 inner: "ok", } b := []byte(`{"nAmE":"Bob","Food":"Pickle", "inner":"changed"}`) err := json.Unmarshal(b, &m) if err != nil { 
 fmt.Printf(err.Error()) 
 return} fmt.Printf("%v", m) Output: {Bob Hello 1294706395881547000 ok}
StructTag

If you want to manually configure the corresponding relationship between the members of the structure and the JSON field, you can define When labeling the structure, label the members:

Use

omitempty to be familiar with, if the field is nil

or 0 value (number 0, string "", empty array [], etc.), the packaged

JSON result will not have this field.

type Message struct { 
 Name string `json:"msg_name"`  // 对应JSON的msg_name 
 Body string `json:"body,omitempty"` // 如果为空置则忽略字段 
 Time int64 `json:"-"`    // 直接忽略字段 } var m = Message{ 
 Name: "Alice", 
 Body: "", 
 Time: 1294706395881547000, } data, err := json.Marshal(m) if err != nil { 
 fmt.Printf(err.Error()) 
 return} fmt.Println(string(data)) Output: {"msg_name":"Alice"}
More flexibility in using JSON

Use json.RawMessage

json .RawMessage is actually a redefinition of the []byte

type. Casting is possible.

Now there is a scenario where the format of one of the fields in the structure is unknown:

type Command struct { 
 ID int 
 Cmd string 
 Args *json.RawMessage 
}
If json.RawMessage is used,

Args# The ## field will not be parsed when

Unmarshal

, and the byte data will be assigned directly to Args. We can first unpack the JSON data of the first layer, and then determine the specific type of Args based on the value of Cmd for the second time Unmarshal. It should be noted here that you must use the pointer type *json.RawMessage, otherwise the Args will be considered

[]byte

Type will be packed into a base64 encoded string when packaging. Using interface{}

interface{}type will automatically Convert JSON to the corresponding data type:

JSON的boolean 转换为boolJSON的数值 转换为float64JSON的字符串 转换为stringJSON的Array 转换为[]interface{}JSON的Object 转换为map[string]interface{}JSON的null 转换为nil

There are two things to note. One is that all JSON values ​​are automatically converted to the float64 type. When used, they need to be manually converted to the required int,

int64

and other types. . The second one is object of JSON which is automatically converted to map[string]interface{} type. When accessing, use JSON ``Object## directly. The field name of # is accessed as key. When you don’t know the format of JSON data, you can use interface{}.

自定义类型

如果希望自己定义对象的打包解包方式,可以实现以下的接口:

type Marshaler interface { 
 MarshalJSON() ([]byte, error) } type Unmarshaler interface { 
 UnmarshalJSON([]byte) error 
}

实现该接口的对象需要将自己的数据打包和解包。如果实现了该接口,json在打包解包时则会调用自定义的方法,不再对该对象进行其他处理。                                                          

The above is the detailed content of Teach you how to use Json in Go. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
Golang vs. C  : Code Examples and Performance AnalysisGolang vs. C : Code Examples and Performance AnalysisApr 15, 2025 am 12:03 AM

Golang is suitable for rapid development and concurrent programming, while C is more suitable for projects that require extreme performance and underlying control. 1) Golang's concurrency model simplifies concurrency programming through goroutine and channel. 2) C's template programming provides generic code and performance optimization. 3) Golang's garbage collection is convenient but may affect performance. C's memory management is complex but the control is fine.

Golang's Impact: Speed, Efficiency, and SimplicityGolang's Impact: Speed, Efficiency, and SimplicityApr 14, 2025 am 12:11 AM

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

C   and Golang: When Performance is CrucialC and Golang: When Performance is CrucialApr 13, 2025 am 12:11 AM

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang in Action: Real-World Examples and ApplicationsGolang in Action: Real-World Examples and ApplicationsApr 12, 2025 am 12:11 AM

Golang excels in practical applications and is known for its simplicity, efficiency and concurrency. 1) Concurrent programming is implemented through Goroutines and Channels, 2) Flexible code is written using interfaces and polymorphisms, 3) Simplify network programming with net/http packages, 4) Build efficient concurrent crawlers, 5) Debugging and optimizing through tools and best practices.

Golang: The Go Programming Language ExplainedGolang: The Go Programming Language ExplainedApr 10, 2025 am 11:18 AM

The core features of Go include garbage collection, static linking and concurrency support. 1. The concurrency model of Go language realizes efficient concurrent programming through goroutine and channel. 2. Interfaces and polymorphisms are implemented through interface methods, so that different types can be processed in a unified manner. 3. The basic usage demonstrates the efficiency of function definition and call. 4. In advanced usage, slices provide powerful functions of dynamic resizing. 5. Common errors such as race conditions can be detected and resolved through getest-race. 6. Performance optimization Reuse objects through sync.Pool to reduce garbage collection pressure.

Golang's Purpose: Building Efficient and Scalable SystemsGolang's Purpose: Building Efficient and Scalable SystemsApr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Why do the results of ORDER BY statements in SQL sorting sometimes seem random?Apr 02, 2025 pm 05:24 PM

Confused about the sorting of SQL query results. In the process of learning SQL, you often encounter some confusing problems. Recently, the author is reading "MICK-SQL Basics"...

Is technology stack convergence just a process of technology stack selection?Is technology stack convergence just a process of technology stack selection?Apr 02, 2025 pm 05:21 PM

The relationship between technology stack convergence and technology selection In software development, the selection and management of technology stacks are a very critical issue. Recently, some readers have proposed...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools