How to add valid json string to object

王林
Release: 2024-02-11 17:51:18
forward
1013 people have browsed it

如何向对象添加有效的 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"`
}
Copy after login

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)
Copy after login

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"`
}
Copy after login

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)
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template