Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lowercase JSON key names with JSON Marshal in Go

People also ask

What does JSON Marshal do in Golang?

We can use the Marshal function to convert Go objects to JSON. The Marshal function comes with the following syntax. It accepts an empty interface. In other words, you can provide any Go data type to the function — an integer, float, string, struct, map, etc.

What is marshal in JSON?

JSON has 3 basic types: booleans, numbers, strings, combined using arrays and objects to build complex structures. 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.

What is JSON marshal and Unmarshal in Golang?

In Golang, struct data is converted into JSON and JSON data to string with Marshal() and Unmarshal() method. The methods returned data in byte format and we need to change returned data into JSON or String. In our previous tutorial, we have explained about Parsing JSON Data in Golang.

What does Marshal mean in Golang?

6 months ago. by John Otieno. Marshaling refers to transforming an object into a specific data format that is suitable for transmission. JSON is one of the most popular data interchange formats.


Have a look at the docs for encoding/json.Marshal. It discusses using struct field tags to determine how the generated json is formatted.

For example:

type T struct {
    FieldA int    `json:"field_a"`
    FieldB string `json:"field_b,omitempty"`
}

This will generate JSON as follows:

{
    "field_a": 1234,
    "field_b": "foobar"
}

You could make your own struct with the keys that you want to export, and give them the appropriate json tags for lowercase names. Then you can copy the desired struct into yours before encoding it as JSON. Or if you don't want to bother with making a local struct you could probably make a map[string]interface{} and encode that.