Closed1
gotipでencoding/json/v2を試す

proposal
で
GOEXPERIMENT=jsonv2
以下で追加された
gotipを有効にする
上のclをdownload
go install golang.org/dl/gotip@latest
go download 665796
gotip mod init
cd ~/anywhere/your/favorite/playground
# or
cd $(mktemp -d)
gotip mod init iikanji-no-namae
goplsのunreleased version入れなくていい
lintは十分動作する+別に構文追加じゃないからかな?
にしたがって入れてもいい。
私はneovimのmasonで管理されているgoplsで動かしていますが例えばjson:",format=RFC3339"
みたいに書き間違えてもwarningが出てた(正しくはformat:RFC3339
)のでなんかもうgopls v0.18.1
で対応してそう。
構文追加の際には必要かもしれないですね。
lsp/gopls.lua
-- gopls from PATH, maybe maosn managed (= latest stable).
local lsCmd = { "gopls" }
if vim.env.GOPLS_PATH ~= nil and vim.env.GOPLS_PATH ~= "" then
-- Can be changed arbitrarily, maybe latest unreleased.
lsCmd = vim.env.GOPLS_PATH
end
return {
cmd = lsCmd,
settings = {
gopls = { -- https://github.com/golang/tools/blob/master/gopls/doc/settings.md
analyses = {
ST1003 = true,
fieldalignment = false,
fillreturns = true,
nilness = true,
nonewvars = true,
shadow = true,
undeclaredname = true,
unreachable = true,
unusedparams = true,
unusedwrite = true,
useany = true,
},
codelenses = {
generate = true, -- show the `go generate` lens.
regenerate_cgo = true,
test = true,
tidy = true,
upgrade_dependency = true,
vendor = true,
},
hints = {
assignVariableTypes = true,
compositeLiteralFields = true,
compositeLiteralTypes = true,
constantValues = true,
functionTypeParameters = true,
parameterNames = true,
rangeVariableTypes = true,
},
buildFlags = { "-tags", "integration" },
completeUnimported = true,
diagnosticsDelay = "500ms",
gofumpt = true,
matcher = "Fuzzy",
semanticTokens = true,
staticcheck = true,
symbolMatcher = "fuzzy",
-- I've used for a while with this option, and found it annoying.
-- Great feature tho.
-- usePlaceholders = true,
},
},
}
gotipをPATHに加えてGOTOOLCHAIN=pathにする
しないとgo1.25(上のgotip mod initで作られる)がダウンロードできなくてエラーになる
export PATH=$(gotip env GOROOT)/bin/:$PATH
export GOTOOLCHAIN=path
GOEXPERIMENT=jsonv2
export GOEXPERIMENT=jsonv2
とりあえず動かしてみる
package main
import (
"encoding/json/jsontext"
"encoding/json/v2"
"fmt"
"time"
)
type A struct {
Foo string `json:"foo,omitzero"`
Bar int `json:"int,omitzero"`
T time.Time `json:"t,omitzero,format:RFC3339"`
}
func main() {
a := A{
Foo: "foo",
Bar: 123,
T: time.Now(),
}
bin, err := json.Marshal(a, jsontext.WithIndent(" "))
if err != nil {
panic(err)
}
fmt.Println(string(bin))
}
$ go run .
{
"foo": "foo",
"int": 123,
"t": "2025-05-11T14:48:17+09:00"
}
このスクラップは4ヶ月前にクローズされました