在Golang中向JSON添加新字段的替代方法有哪些
在Golang中向JSON添加新字段的替代方法有哪些 https://play.golang.org/p/548a20mPSoR
import (
"encoding/json"
"fmt"
"log"
"os/exec"
"strings"
)
type Company struct {
ID struct {
Oid string `json:"$oid"`
} `json:"_id"`
Name string `json:"name"`
Pin string `json:"Pin"`
}
func (c Company) MarshalJSON() ([]byte, error) {
uuid, _ := exec.Command("uuidgen").Output()
uuid0 := strings.ReplaceAll(string(uuid),"\n","")
le := len(strings.Split(c.Name, " "))
conc := c.Name[:5] + " " + c.Pin[:5]
n := struct {
Name string `json:"name"`
Pin string `json:"pin"`
Pid string `json:"pid"`
Words int `josn:"words"`
Dummy string `json:"dummy"`
}{
Name: c.Name,
Pin: c.Pin,
Pid: uuid0,
Words: le,
Dummy: conc,
}
ans, error:= json.Marshal(n)
if error !=nil {
log.Fatal(error)
}
return ans, error
}
func main() {
data := []byte(`[{"_id": {"$oid": "585cbb871"}, "name": "Pqr Mn", "pin": "U2334"}, {"_id": {"$oid": "305a6776912"}, "name": "Abc Xyz", "pin": "U12345"}, {"_id": {"$oid": "5a704ed1b"}, "name": "Lbs Ll", "pin": "U34567"}]`)
c := []Company{}
error := json.Unmarshal(data,&c)
if error != nil{
log.Fatal(error)
}
out, _ := json.Marshal(c)
fmt.Println(string(out))
}
更多关于在Golang中向JSON添加新字段的替代方法有哪些的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复
更多关于在Golang中向JSON添加新字段的替代方法有哪些的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在Golang中向JSON添加新字段有多种替代方法。以下是几种常见方案:
1. 使用嵌套结构体组合
type Company struct {
ID struct { Oid string `json:"$oid"` } `json:"_id"`
Name string `json:"name"`
Pin string `json:"pin"`
}
type CompanyWithExtra struct {
Company
Pid string `json:"pid"`
Words int `json:"words"`
Dummy string `json:"dummy"`
}
func main() {
data := []byte(`{"_id": {"$oid": "585cbb871"}, "name": "Pqr Mn", "pin": "U2334"}`)
var c Company
json.Unmarshal(data, &c)
// 添加额外字段
cw := CompanyWithExtra{
Company: c,
Pid: "new-uuid",
Words: len(strings.Split(c.Name, " ")),
Dummy: c.Name[:5] + " " + c.Pin[:5],
}
out, _ := json.Marshal(cw)
fmt.Println(string(out))
}
2. 使用map[string]interface{}
func addFieldsViaMap(companyJSON []byte) ([]byte, error) {
var m map[string]interface{}
if err := json.Unmarshal(companyJSON, &m); err != nil {
return nil, err
}
// 添加新字段
m["pid"] = "generated-uuid"
m["words"] = len(strings.Split(m["name"].(string), " "))
m["dummy"] = m["name"].(string)[:5] + " " + m["pin"].(string)[:5]
return json.Marshal(m)
}
3. 使用json.RawMessage进行部分解析
type CompanyPartial struct {
ID json.RawMessage `json:"_id"`
Name string `json:"name"`
Pin string `json:"pin"`
}
type CompanyExtended struct {
ID json.RawMessage `json:"_id"`
Name string `json:"name"`
Pin string `json:"pin"`
Pid string `json:"pid"`
Words int `json:"words"`
Dummy string `json:"dummy"`
}
func extendCompany(data []byte) ([]byte, error) {
var cp CompanyPartial
if err := json.Unmarshal(data, &cp); err != nil {
return nil, err
}
ce := CompanyExtended{
ID: cp.ID,
Name: cp.Name,
Pin: cp.Pin,
Pid: "new-pid",
Words: len(strings.Split(cp.Name, " ")),
Dummy: cp.Name[:5] + " " + cp.Pin[:5],
}
return json.Marshal(ce)
}
4. 使用第三方库如sjson
import "github.com/tidwall/sjson"
func addFieldsWithSJSON(companyJSON []byte) ([]byte, error) {
// 添加单个字段
result, _ := sjson.SetBytes(companyJSON, "pid", "uuid-value")
// 添加多个字段
result, _ = sjson.SetBytes(result, "words", 2)
result, _ = sjson.SetBytes(result, "dummy", "Pqr M U233")
return []byte(result), nil
}
5. 自定义MarshalJSON的改进版本
func (c Company) MarshalJSON() ([]byte, error) {
type Alias Company
aux := struct {
Alias
Pid string `json:"pid"`
Words int `json:"words"`
Dummy string `json:"dummy"`
}{
Alias: Alias(c),
Pid: generateUUID(),
Words: len(strings.Split(c.Name, " ")),
Dummy: c.Name[:5] + " " + c.Pin[:5],
}
return json.Marshal(aux)
}
func generateUUID() string {
uuid, _ := exec.Command("uuidgen").Output()
return strings.TrimSpace(string(uuid))
}
6. 使用结构体标签和omitempty
type CompanyExtended struct {
ID struct { Oid string `json:"$oid"` } `json:"_id"`
Name string `json:"name"`
Pin string `json:"pin"`
Pid string `json:"pid,omitempty"`
Words int `json:"words,omitempty"`
Dummy string `json:"dummy,omitempty"`
}
func marshalWithOptionalFields(c Company) ([]byte, error) {
ce := CompanyExtended{
ID: c.ID,
Name: c.Name,
Pin: c.Pin,
Pid: "optional-pid",
}
// 只有在需要时才添加额外字段
if addExtraFields {
ce.Words = len(strings.Split(c.Name, " "))
ce.Dummy = c.Name[:5] + " " + c.Pin[:5]
}
return json.Marshal(ce)
}
这些方法各有适用场景:结构体组合适合类型安全场景,map适合动态字段,第三方库适合复杂操作,自定义MarshalJSON适合完全控制序列化过程。

