如何将有效的 JSON 字符串添加到对象中?

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

How to add a valid json string to an object

问题

我目前有这样的代码:

type Info struct {
    Ids        []string `json:"ids"`
    assignment string   `json:"assignment"`
}

现在我的assignment是一个大的硬编码的 JSON 字符串,从文件中读取。我正在做这样的事情:

r := Info{Ids: names, assignment: existingJsonString}
body, _ := json.Marshal(r)

然而,上面的body是不正确的,因为assignment出现为字符串而不是 JSON 对象。我该如何告诉Info结构体,assignment将是一个 JSON 字符串而不是普通字符串,以便json.Marshal可以正确处理它?

英文:

I currently have something like this

type Info struct {
	Ids        []string `json:"ids"`
	assignment string   `json:"assignment"`
}

Now my assignment is a large hardcoded json string that is read from a file.
I am doing something like this

r := Info{Ids: names, assignment: existingJsonString}
body, _ := json.Marshal(r)

However the above body is incorrect as assignment appears as string and not a json object. How can I tell the info struct that assignment will be a json string and not a regular string so that json.Marshal plays well with it ?

答案1

得分: 3

使用类型 json.RawMessage,请注意 assignment 应该是可导出的:

type Info struct {
    Ids        []string        `json:"ids"`
    Assignment json.RawMessage `json:"assignment"`
}

示例:

package main

import (
    "encoding/json"
    "fmt"
)

type Info struct {
    Ids        []string        `json:"ids"`
    Assignment json.RawMessage `json:"assignment"`
}

func main() {
    r := Info{
        Ids:        []string{"id1", "id2"},
        Assignment: json.RawMessage(`{"a":1,"b":"str"}`),
    }
    body, err := json.Marshal(r)
    if err != nil {
        panic(err)
    }

    fmt.Printf("%s\n", body)
}
英文:

Use the type json.RawMessage, and please note that assignment should be exported:

type Info struct {
	Ids        []string        `json:"ids"`
	Assignment json.RawMessage `json:"assignment"`
}

Example:

package main

import (
	"encoding/json"
	"fmt"
)

type Info struct {
	Ids        []string        `json:"ids"`
	Assignment json.RawMessage `json:"assignment"`
}

func main() {
	r := Info{
		Ids:        []string{"id1", "id2"},
		Assignment: json.RawMessage(`{"a":1,"b":"str"}`),
	}
	body, err := json.Marshal(r)
	if err != nil {
		panic(err)
	}

	fmt.Printf("%s\n", body)
}

huangapple
  • 本文由 发表于 2023年7月16日 06:49:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76696049.html
匿名

发表评论

匿名网友

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

确定