Home >Backend Development >Golang >How to hide a certain field in golang json

How to hide a certain field in golang json

尚
Original
2019-12-13 14:10:136376browse

How to hide a certain field in golang json

Usage scenario: Respond to API callers with json data in go.

1. Some fields are not exposed to users.

2. Some fields control whether there is such data based on the user's level.

The Id field is not exposed to users, so use `json:"-"` to modify it.

Inputs and Outputs do not return field data in some cases.

(1), use `json:"omitempty"` (ignore this field when the field is empty) to modify the field;

(2), when the field is not required to be returned, let Its assigned value can be empty.

Golang json method to hide a field example:

The following structure, I want to ignore the DataSource field when formatting it as json

type RealTimeData struct {
    Code           string   `json:"code"`
    Time           time.Time    `json:"time"`
    OpenPrice      float32  `json:"openPrice"`
    PrevClosePrice float32  `json:"prevClosePrice"`
    LastPrice      float32  `json:"lastPrice"`
    HighPrice      float32  `json:"highPrice"`
    LowPrice       float32  `json:"lowPrice"`
    MarketValue    float32  `json:"marketValue"`
    PER            float32  `json:"per"`    // static price/earning ration
    PBR            float32  `json:"pbr"` // price/book ration
    DataSource     string}

As shown below, change it Specify as "-"

DataSource     string   `json:"-"`

How to hide a certain field in golang json

For more golang knowledge, please pay attention to the go language tutorial column.

The above is the detailed content of How to hide a certain field in golang json. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn