JSON
Content-Type: "application/json"
The Context.JSON(v, ...opts) is the method which sends JSON responses to the client. It accepts the value and optional settings for rendering. The JSON options structure looks like this:
1
// JSON contains the options for the JSON (Context's) Renderer.
2
type JSON struct {
3
// http-specific
4
StreamingJSON bool
5
// content-specific
6
UnescapeHTML bool
7
Indent string
8
Prefix string
9
ASCII bool
10
// if true then it prepends a "while(1);" when Go slice (to JSON Array) value.
11
Secure bool
12
// proto.Message specific marshal options.
13
Proto ProtoMarshalOptions
14
}
Copied!
If Indent field is empty and the application runs without optimizations, the Indent field will be automatically set to 2 spaces.
So, if we want to write a JSON with indentation of four spaces and prefixed with while(1) we can do something like that:
1
func handler(ctx iris.Context) {
2
response := []string{"val1", "val2", "val3"}
3
options := iris.JSON{Indent: " ", Secure: true}
4
ctx.JSON(response, options)
5
}
Copied!
Result
1
while(1);[
2
"val1",
3
"val2",
4
"val3"
5
]
Copied!
As with all RESTful rich responses, any marshallable (JSON at this case) Go type can be given. If we want to render a Go struct as JSON, the struct's fields we want to render should be exported, and optionally tagged with the json struct tag. Look the exaple below:
1
type User struct {
2
Firstname string `json:"firstname"`
3
Lastname string `json:"lastname"`
4
IgnoredField int `json:"-"`
5
}
6
7
func handler(ctx iris.Context) {
8
response := User{
9
Firstname: "makis",
10
Lastname: "maropoulos",
11
IgnoredField:42,
12
}
13
14
ctx.JSON(response)
15
}
Copied!
Result
1
{
2
"firstname": "makis",
3
"lastname": "maropoulos"
4
}
Copied!

ASCII

Use the ASCII field to generate ASCII-only JSON with escaped non-ASCII characters.
1
app.Get("/json_ascii", func(ctx iris.Context) {
2
response := iris.Map{"lang": "GO-虹膜", "tag": "<br>"}
3
options := iris.JSON{Indent: " ", ASCII: true}
4
ctx.JSON(response, options)
5
})
Copied!
Result
1
{
2
"lang": "GO-\u8679\u819c",
3
"tag": "\u003cbr\u003e"
4
}
Copied!

UnescapeHTML

Do not replace special HTML characters with their unicode entities using the UnescapeHTML field.
1
app.Get("/json_raw", func(ctx iris.Context) {
2
options := iris.JSON{UnescapeHTML: true}
3
ctx.JSON(iris.Map{
4
"html": "<b>Hello, world!</b>",
5
}, options)
6
})
Copied!
Result
1
{"html":"<b>Hello, world!</b>"}
Copied!
Last modified 1yr ago
Export as PDF
Copy link