Home > Backend Development > Golang > How to remove apostrophe/byte marks from string sentences when trying to parse yaml

How to remove apostrophe/byte marks from string sentences when trying to parse yaml

WBOY
Release: 2024-02-05 22:45:11
forward
1197 people have browsed it

"尝试解析

Question content

Here is an example

The yaml parsing library seems to be unable to print" So when I parse a sentence with " , go adds byte apostrophes (')

around it

Is there some trick to get it to print/make a simple string/quote string without adding byte apostrophes?

Sample code:

import (
    "fmt"
    "log"

    yaml "gopkg.in/yaml.v3"
)

type X struct {
    Example string `yaml:"some-example"`
}

func main() {
    item := X{
        Example: fmt.Sprint("\"some text\""),
    }

    res, err := yaml.Marshal(item)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Print(string(res))
}
Copy after login

Print some-example: '"some text"'

Wantsome-example:"some text"


Correct answer


Is there some trick to make it easy to print/make string/quoted string without adding byte apostrophes?

Please note that you are printing the output of yaml.marshal, i.e. you are printing a valid yaml document, and the yaml does not have anything called "byte apostrophes". In yaml, a string can be without quotes, double quotes, or single quotes, no matter what, they are all characters string.

# all three are strings 
a: foo bar
b: "foo bar"
c: 'foo bar'
Copy after login

So your raw output

some-example: '"some text"'
Copy after login

is perfectly valid yaml, it's not go that adds the single quotes, it's ngopkg.in/yaml.v3 which is what the package does.

afaict There is no way to set global settings for yaml.encoder Use the double quote style to marshal each string, but you can use the implementation yaml.marshaler Force yaml.encoder to always output a double-quoted string for any value of this custom type.

For example:

type doublequotedstring string

func (s doublequotedstring) marshalyaml() (interface{}, error) {
    return yaml.node{
        kind:  yaml.scalarnode,
        style: yaml.doublequotedstyle, // <- this is the relevant part
        value: string(s),
    }, nil
}
Copy after login

https://www.php.cn/link/99701e768d9a09b314e43a1d9e3e9dfa

some-example: "\"some text\""
Copy after login

The above is the detailed content of How to remove apostrophe/byte marks from string sentences when trying to parse yaml. 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