json
Examples of how to parse (unmarshal) and stringify (marshal) JSON.
# Node.js
let jsonstr = '{"foo":"bar"}';
let parsed = JSON.parse(jsonstr);
console.log(parsed);
jsonstr = JSON.stringify(parsed);
console.log(jsonstr);
1
2
3
4
5
6
7
2
3
4
5
6
7
Output
{ foo: 'bar' }
{"foo":"bar"}
1
2
2
# Go
package main
import (
"encoding/json"
"fmt"
)
type T struct {
Foo string `json:"foo"`
}
func main() {
jsonstr := `{"foo":"bar"}`
t := new(T)
err := json.Unmarshal([]byte(jsonstr), t)
if err != nil {
panic(err)
}
fmt.Println(t)
marshalled, err := json.Marshal(t)
jsonstr = string(marshalled)
fmt.Println(jsonstr)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Output
&{bar}
{"foo":"bar"}
1
2
2
编辑 (opens new window)
上次更新: 2022/09/30, 11:34:22