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共享数据用Mutex 或 Channel

在go 里,多线程对共享数据的操作一般要使用Mutex 或 Channel 来加锁或隔离通信。下面是一个使用Mutex 和 Channel 比较的例子。...

Golang Range 的性能提升Tip

Go 语言里使用 range 可以方便遍历数组(array)、切片(slice)、字典(map)和信道(chan)。这里主要关注他们的性能。...

Golang实现简单的Socks5代理

Socks5 代理较 `http/https` 代理有较好的性能,下面是借鉴某个著名开源软件的 local 实现的简单代理。...

Golang Web 程序生产环境独立部署示例

一个 web 应用通常是跑在一个前端代理,如 Nginx 后,这样可以方便的在同一个服务器部署多个应用。这里说的独立部署是指让 go web 程序直接暴露在外面,独占 443、80 端口(俗称裸跑)。这样做除了性能有些提高外,更重要的是部署方便。...

Golang http IPv4/IPv6 服务

Golang 的网络服务,如果不指定IPv4 或 IPv6,如果VPS 同时支持 IPv4 和 IPv6,`net.Listen()` 只会监听 IPv6 地址。但这不影响客户端使用 IPv4 地址来访问。...

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

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 0ms