Golang在解析JSON时删除字符串前缀

huangapple go评论124阅读模式
英文:

Golang remove string prefix when unmarshalling JSON

问题

在我的 JSON 数据结构中,有一个字符串可能带有前缀。在解组 JSON 时,是否可以有一个函数来移除该前缀?我正在研究在 Golang 中自定义 JSON 解组,并试图利用它。

例如,有效载荷可以是以下任一形式:

{
"id": "urn:uuid:1234567890"
}

{
"id": "1234567890"
}

当我执行 JSON.unmarshall(data, &struct) 时,我希望解组函数能够处理并移除字符串中的 urn:uuid 前缀,以便结构体的 id 始终为值 1234567890

英文:

In my json data structure I have a string that can have a prefix. When unmarshalling JSON, is it possible to have a function to remove that prefix? I am looking into custom JSON unmarshalling in golang and trying to leverage that.

For example. The payload can be either of the following

{
  "id": "urn:uuid:1234567890"
}

{
  "id": "1234567890"
}

When I do JSON.unmarshall(data, &struct) I'd like the unmarshall function to handle removing the urn:uuid prefix from the string if it is there so the struct will always have the value 1234567890 for id.

答案1

得分: 4

你可以在需要修剪的数据上提供一个自定义的UnmarshalJSON方法,下面是一个示例实现。如果你需要使用正则表达式匹配开头而不是匹配固定字符串(或字节数组),可能需要进行扩展:

package main

import (
	"bytes"
	"encoding/json"
	"log"
)

var (
	sampleJSON   = []byte(`{"id": "urn:uuid:1234567890"}`)
	prefixToTrim = []byte(`urn:uuid:`)
)

type IDField string

type Data struct {
	ID IDField `json:"id"`
}

func main() {
	d := &Data{}
	err := json.Unmarshal(sampleJSON, d)
	if err != nil {
		log.Fatal(err)
	}

	log.Println(d.ID)
}

// UnmarshalJSON provides custom unmarshalling to trim `urn:uuid:` prefix from IDField
func (id *IDField) UnmarshalJSON(rawIDBytes []byte) error {

	// trim quotes and prefix
	trimmedID := bytes.TrimPrefix(bytes.Trim(rawIDBytes, `"`), prefixToTrim)

	// convert back to id field & assign
	*id = IDField(trimmedID)
	return nil
}

go playground

英文:

You can provide a custom UnmarshalJSON method on the data you need to trim, here is an example implementation, you may need to extend if you have to regex match the start rather than match hard string (or byte array in this case):

go playground

package main

import (
	"bytes"
	"encoding/json"
	"log"
)

var (
	sampleJSON   = []byte(`{"id": "urn:uuid:1234567890"}`)
	prefixToTrim = []byte(`urn:uuid:`)
)

type IDField string

type Data struct {
	ID IDField `json:"id"`
}

func main() {
	d := &Data{}
	err := json.Unmarshal(sampleJSON, d)
	if err != nil {
		log.Fatal(err)
	}

	log.Println(d.ID)
}

// UnmarshalJSON provides custom unmarshalling to trim `urn:uuid:` prefix from IDField
func (id *IDField) UnmarshalJSON(rawIDBytes []byte) error {

	// trim quotes and prefix
	trimmedID := bytes.TrimPrefix(bytes.Trim(rawIDBytes, `"`), prefixToTrim)

	// convert back to id field & assign
	*id = IDField(trimmedID)
	return nil
}

huangapple
  • 本文由 发表于 2017年9月7日 02:20:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/46081919.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定