深色模式
Go 手动读取 json(pull 方式)
jsoniter 库
jsoniter 能以极低的成本,替换标准库,性能明显高于标准库。
同时,jsoniter 也可以手动解析 json,灵活度更高。
安装 jsoniter:
sh
go get github.com/json-iterator/go
导入 jsoniter:
go
import (
// ...
jsoniter "github.com/json-iterator/go"
)
手动解析
解析 object
go
func main() {
iter := jsoniter.ParseString(jsoniter.ConfigDefault, `
{
"name": "Cake",
"weight": 150,
"price": 18.8
}
`)
for field := iter.ReadObject(); field != ""; field = iter.ReadObject() {
switch field {
case "name":
name := iter.ReadString()
fmt.Printf("name: %s\n", name)
case "price":
price := iter.ReadFloat32()
fmt.Printf("price: %.2f\n", price)
default:
iter.Skip()
}
}
}
output:
name: Cake
price: 18.80
解析 array
go
func main() {
iter := jsoniter.ParseString(jsoniter.ConfigDefault, `
[
{
"name": "Cake",
"price": 18.8,
"weight": 150
},
{
"name": "Sugar",
"price": 7.5,
"weight": 500
}
]
`)
for iter.ReadArray() {
for field := iter.ReadObject(); field != ""; field = iter.ReadObject() {
switch field {
case "name":
name := iter.ReadString()
fmt.Printf("name: %s\n", name)
case "price":
price := iter.ReadFloat32()
fmt.Printf("price: %.2f\n", price)
default:
iter.Skip()
}
}
}
}
output:
name: Cake
price: 18.80
name: Sugar
price: 7.50