教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 golang 处理json_使用Go进行JSON处理

golang 处理json_使用Go进行JSON处理

发布时间:2023-03-17   编辑:jiaochengji.com
教程集为您提供golang 处理json,使用Go进行JSON处理等资源,欢迎您收藏本站,我们将为您提供最新的golang 处理json,使用Go进行JSON处理资源

golang 处理json

JSON stands for JavaScript Object Notation, and it’s a very handy way of exchanging structured data. And it’s very popular, especially when interacting with APIs.

JSON代表JavaScript Object Notation,它是交换结构化数据的一种非常方便的方法。 它非常流行,尤其是在与API交互时。

Go has top-level support for JSON in its standard library, with the encoding/json package.

Go在其标准库中使用encoding/json对JSON提供了顶级支持。

Compared to loosely typed languages, decoding JSON is more complicated. In JavaScript, all you need to do is JSON.parse(). Python has json.loads(), and PHP has json_decode(). They just dump values without problems, but being Go strongly typed, you need to do a little bit more work to match the types.

与松散类型的语言相比,解码JSON更为复杂。 在JavaScript中,您所需要做的就是JSON.parse() 。 Python具有json.loads() ,而PHP具有json_decode() 。 它们只是转储值而没有问题,但是要进行强类型化,您需要做更多的工作来匹配类型。

JSON has 3 basic types: booleans, numbers, strings, combined using arrays and objects to build complex structures.

JSON具有3种基本类型: 布尔值数字字符串 ,使用数组对象组合以构建复杂的结构。

Go’s terminology calls marshal the process of generating a JSON string from a data structure, and unmarshal the act of parsing JSON to a data structure.

Go的术语调用封送了从数据结构生成JSON字符串的过程,并封送了将JSON解析为数据结构的操作。

A JSON string

JSON字符串

input := `{"firstname": "Bill", "surname": "Gates"}`

解组JSON (Unmarshal JSON)

Here is a JSON example taken from Mozilla’s MDN

这是取自Mozilla的MDN的JSON示例

{
  "squadName": "Super hero squad",
  "homeTown": "Metro City",
  "formed": 2016,
  "secretBase": "Super tower",
  "active": true,
  "members": [
    {
      "name": "Molecule Man",
      "age": 29,
      "secretIdentity": "Dan Jukes",
      "powers": [
        "Radiation resistance",
        "Turning tiny",
        "Radiation blast"
      ]
    },
    {
      "name": "Madame Uppercut",
      "age": 39,
      "secretIdentity": "Jane Wilson",
      "powers": [
        "Million tonne punch",
        "Damage resistance",
        "Superhuman reflexes"
      ]
    },
    {
      "name": "Eternal Flame",
      "age": 1000000,
      "secretIdentity": "Unknown",
      "powers": [
        "Immortality",
        "Heat Immunity",
        "Inferno",
        "Teleportation",
        "Interdimensional travel"
      ]
    }
  ]
}

How can we parse it into a Go data structure? We need a matching data structure, of course. We have 5 basic types, and an array of objects. Let’s start with the basic types:

我们如何将其解析为Go数据结构? 当然,我们需要一个匹配的数据结构。 我们有5种基本类型和一系列对象。 让我们从基本类型开始:

type squad struct {
    SquadName string
    HomeTown string
    Formed int
    SecretBase string
    Active bool
}

We need to define the JSON as a []byte, like this:

我们需要将JSON定义为[]byte ,如下所示:

input := []byte(`
    {
        "squadName": "Super hero squad",
        [...]
    }
`)

And we can unmarshal the JSON to a squad instance:

我们可以将JSON解组到一个小队实例:

s := squad{}
err := json.Unmarshal(input, &s)
if err != nil {
    panic(err)
}
fmt.Printf("%v", s)

This will print

这将打印

{Super hero squad Metro City 2016 Super tower true}

play

Notice how we don’t have any error complaining about the missing match between JSON values and our struct, they are ignored.

请注意,对于JSON值与结构之间缺少匹配的抱怨,我们没有任何错误,它们将被忽略。

Let’s make sure json.Unmarshal() will get us all the fields, with:

让我们确保json.Unmarshal()将获得我们所有的字段,其中包括:

type squad struct {
	SquadName  string
	HomeTown   string
	Formed     int
	SecretBase string
	Active     bool
	Members    []Member
}

type Member struct {
	Name           string
	Age            int
	SecretIdentity string
	Powers         []string
}

play

Remember to have public (uppercase) properties in your structs.

记住要在结构中具有公共(大写)属性。

重命名JSON字段名称 (Renaming JSON field names)

In this case, all was fine because the JSON had compatible file names. What if you want to map the JSON to other fields in your struct?

在这种情况下,一切都很好,因为JSON具有兼容的文件名。 如果要将JSON映射到结构中的其他字段怎么办?

For example, what if the Member name is passed as member_name, but you want it to be stored in Name instead?

例如,如果将成员名称作为member_name传递,但是您希望将其存储在Name怎么办?

Use this syntax:

使用以下语法:

type Member struct {
	Name string `json:"member_name"`
}

忽略JSON字段 (Ignoring JSON fields)

Use this syntax:

使用以下语法:

type Member struct {
	Name string `json:"-"`
}

and Name field will be ignored when marshaling/unmarshaling.

封送/取消封送时,“名称”字段将被忽略。

转换JSON字段类型 (Converting JSON field types)

You can use tags to annotate the type that the JSON will be converted to:

您可以使用标记来注释将JSON转换为的类型:

type Member struct {
    Age       int `json:"age,string"`
}

The Member struct has an Age property that’s represented as an int. What if you want it to be a string instead, but JSON passes an int?

Member结构具有一个Age属性,该属性表示为int 。 如果您希望将其改为string ,但JSON传递一个int怎么办?

Use the type annotation:

使用类型注释:

type Member struct {
    Age       json.Number `json:"age,Number"`
}

The Number type is an alias for string.

Number类型是string的别名。

Learn more about tags in Go Tags explained

在Go标签中进一步了解标签

元帅JSON (Marshal JSON)

We might now want to build a JSON string from our data structures. For example, this could be a program that takes an country code, and returns the corresponding country details in JSON format.

现在,我们可能想根据我们的数据结构构建一个JSON字符串。 例如,这可能是一个使用国家代码的程序,并以JSON格式返回相应的国家/地区详细信息。

package main

import (
	"encoding/json"
	"fmt"
)

type country struct {
	Name string
}

func main() {
	country_code := "US"

	the_country := country{}

	switch country_code {
	case "US":
		the_country.Name = "United States"
	}

	c, err := json.Marshal(the_country)
	if err != nil {
		panic(err)
	}

	// c is now a []byte containing the encoded JSON
	fmt.Print(string(c))
}

play

When executed, this program will print {"Name":"United States"}.

执行后,该程序将打印{"Name":"United States"}

json.Marshal() returns a []byte, so we must cast it to string when passing it to fmt.Print(), otherwise you’ll see a list of apparently meaningless numbers (but they are meaningful, as they are the actual bytes that compose the string).

json.Marshal()返回一个[]byte ,因此在将其传递给fmt.Print() ,必须将其转换为字符串,否则您会看到一个明显无意义的数字列表(但它们是有意义的,因为它们是实际的组成字符串的字节)。

json.Marshal() will correctly process basic and composit types like slices and maps.

json.Marshal()将正确处理基本类型和复合类型,例如切片和地图。

阅读更多 (Read more)

Read more on the Go blog and in the encoding/json package doc

在Go博客和encoding/json包doc中阅读更多内容

翻译自: https://flaviocopes.com/go-json/

golang 处理json

到此这篇关于“golang 处理json_使用Go进行JSON处理”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
Golang解析json数据之延迟解码
想系统学习GO语言(Golang
处理json数据的原理_3分钟微文档:Go语言解析Json文件,你值得收藏
gin定义统一处理错误
golang json[]
Golang中JSON的使用
golang 结构体struct 标签tag 简介
关于Golang的介绍
golang 网络编程(10)文本处理
Golang 中的 Tags

[关闭]
~ ~