Home > Article > Backend Development > How to remove apostrophe/byte marks from string sentences when trying to parse yaml
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 ('
)
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)) }
Print some-example: '"some text"'
Wantsome-example:"some text"
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'
So your raw output
some-example: '"some text"'
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 }
https://www.php.cn/link/99701e768d9a09b314e43a1d9e3e9dfa
some-example: "\"some text\""
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!