Live example here
It seems like the yaml parsing library is unable to print "
So when i parse a sentence with "
, go adds byte apostrophe around it ('
)
Is there some trick to just have it print/make simple string/quotation string, without the byte apostrophes added?
Example 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))
}
Prints some-example: '"some text"'
Want some-example: "some text"
CodePudding user response:
Is there some trick to just have it print/make simple string/quotation string, without the byte apostrophes added?
Note that you are printing the output of yaml.Marshal
, i.e. you are printing a valid YAML document and YAML does not have anything called "byte apostrophes". In YAML strings can be either unquoted, double quoted, or single quoted, regardless, they are all strings.
# all three are strings
a: foo bar
b: "foo bar"
c: 'foo bar'
So your original output
some-example: '"some text"'
is perfectly valid YAML, and it is not Go that is adding the single quotes, it is the gopkg.in/yaml.v3
package that's doing that.
AFAICT it is not possible to set a global setting for the yaml.Encoder
to marshal every string using the double-quoted style, however you can use a custom string that implements yaml.Marshaler
to force the yaml.Encoder
to always output double quoted strings for any value of that 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://go.dev/play/p/o9VNL5mKdSl
some-example: "\"some text\""