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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:编程工作室 设计师:CSDN官方博客 返回首页
评论
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值