GolangNote

Golang笔记

Golang 超快JSON 解析

Permalink

Golang 超快JSON 解析,基于 github.com/json-iterator/go

Go: JSON 解析
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package main

import (
	"fmt"
	"reflect"
	"unsafe"

	"github.com/json-iterator/go"
)

type StructOfTag struct {
	field1 string `json:"field-1"`
	field2 string `json:"-"`
	field3 int    `json:",string"`
}

func str2byte(s string) []byte {
	x := (*[2]uintptr)(unsafe.Pointer(&s))
	h := [3]uintptr{x[0], x[1], x[1]}
	return *(*[]byte)(unsafe.Pointer(&h))
}
func byte2str(b []byte) string {
	return *(*string)(unsafe.Pointer(&b))
}

func b2s(b []byte) string {
	return *(*string)(unsafe.Pointer(&b))
}

// s2b converts string to a byte slice without memory allocation.
//
// Note it may break if string and/or slice header will change
// in the future go versions.
func s2b(s string) []byte {
	sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
	bh := reflect.SliceHeader{
		Data: sh.Data,
		Len:  sh.Len,
		Cap:  sh.Len,
	}
	return *(*[]byte)(unsafe.Pointer(&bh))
}

func main() {

	struct_ := StructOfTag{}
	//jsoniter.Unmarshal([]byte(`{"field-1": "hello", "field2": "", "field3": "100"}`), &struct_)
	jsoniter.Unmarshal(s2b(`{"field-1": "hello", "field2": "", "field3": "100"}`), &struct_)

	fmt.Println(struct_)

}

输出:

JSON: output
1
{hello  100}

更新

这个库已经能完全兼容标准库 encoding/json,在使用中只需重新定义 json,线程安全!

Go: 代替标准库
1
2
3
4
5
6
import jsoniter "github.com/json-iterator/go"

var json = jsoniter.ConfigCompatibleWithStandardLibrary

json.Marshal(&data)
json.Unmarshal(input, &data)

本文网址: https://golangnote.com/topic/143.html 转摘请注明来源

Related articles

Golang 把cookie 字符串解析为cookie 结构

在做爬虫时有时候会遇到需要带已登录的 cookie 请求,这个时候最简单的方法是在浏览器登录后,在开发者面板找到cookie 字符串,然后拷贝粘贴。这就面临一个问题需要把cookie 字符串解析成Go 语言 cookie 结构体。...

Golang 泛型性能初识

编程时,我们通常需要编写“泛型”函数,其中确切的数据类型并不重要。例如,您可能想编写一个简单的函数来对数字进行求和。Go 直到最近才有这个概念,但最近才添加了它(从1.18版开始)。...

golang snappy 的使用场合

google 自家的 snappy 压缩优点是非常高的速度和合理的压缩率。压缩率比 gzip 小,CPU 占用小。...

Write a Comment to "Golang 超快JSON 解析"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 1ms