php Xiaobian Yuzai introduces you how to add a valid json string to an object. During the development process, we often need to convert data into json format and transmit it to the front-end or other systems. However, sometimes we need to add new data to an existing json object, which requires us to parse, operate and splice json strings. In this article, we will introduce a simple and effective method to implement this function to help you better process json data.
I currently have something like this
type info struct { ids []string `json:"ids"` assignment string `json:"assignment"` }
Right now my assignment
is a large hardcoded json string read from a file.
I'm doing something like this
r := Info{Ids: names, assignment: existingJsonString} body, _ := json.Marshal(r)
But the body
above is incorrect because the assignment appears as a string instead of a json object. How do I tell the info structure assignment
will be a json string instead of a regular string so that json.marshal
can work well with it?
Use type json.rawmessage, 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) }
The above is the detailed content of How to add valid json string to object. For more information, please follow other related articles on the PHP Chinese website!