Home  >  Article  >  Backend Development  >  How to add valid json string to object

How to add valid json string to object

王林
王林forward
2024-02-11 17:51:18964browse

如何向对象添加有效的 json 字符串

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.

Question content

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?

Solution

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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete