How to convert newlines to proper JSON in GO? [duplicate]












1
















This question already has an answer here:




  • What is the difference between backticks (``) & double quotes (“”) in golang?

    3 answers




I have some strings that I'd like to convert to JSON. Using encoding/json here, haven't tried other packages.



The strings may contain newlines and other stuff that breaks JSON if saved as-is.



It works if I pass a string literal - it adds backslashes in front of backslashes. It doesn't work if I just pass a regular string. I can't seem to figure out if there is a way to use variables that contain string literals.



edit: as pointed out, these are not the same values and I kind of understand that, but it doesn't help me solve my problem.



The sample code:



package main

import (
"fmt"
"encoding/json"
)

func main() {
type Test struct {
Input string
}
regularString := Test{"asdnqwe"}
out, err := json.Marshal(regularString)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(out))

literalString := Test{`asdnqwe`}
out, err = json.Marshal(literalString )
if err != nil {
fmt.Println(err)
}
fmt.Println(string(out))
}









share|improve this question















marked as duplicate by Flimzy, Volker go
Users with the  go badge can single-handedly close go questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 14 '18 at 8:54


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.



















  • What is the output you expect in your sample? If it makes it clearer, I've added a couple of extra Printlns that show the strings being encoded in the go playground here. Note the first has an actual new line, the second has a n which will be encoded as \n in json to prevent it being interpreted as a new line.

    – Hugh
    Nov 14 '18 at 10:51
















1
















This question already has an answer here:




  • What is the difference between backticks (``) & double quotes (“”) in golang?

    3 answers




I have some strings that I'd like to convert to JSON. Using encoding/json here, haven't tried other packages.



The strings may contain newlines and other stuff that breaks JSON if saved as-is.



It works if I pass a string literal - it adds backslashes in front of backslashes. It doesn't work if I just pass a regular string. I can't seem to figure out if there is a way to use variables that contain string literals.



edit: as pointed out, these are not the same values and I kind of understand that, but it doesn't help me solve my problem.



The sample code:



package main

import (
"fmt"
"encoding/json"
)

func main() {
type Test struct {
Input string
}
regularString := Test{"asdnqwe"}
out, err := json.Marshal(regularString)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(out))

literalString := Test{`asdnqwe`}
out, err = json.Marshal(literalString )
if err != nil {
fmt.Println(err)
}
fmt.Println(string(out))
}









share|improve this question















marked as duplicate by Flimzy, Volker go
Users with the  go badge can single-handedly close go questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 14 '18 at 8:54


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.



















  • What is the output you expect in your sample? If it makes it clearer, I've added a couple of extra Printlns that show the strings being encoded in the go playground here. Note the first has an actual new line, the second has a n which will be encoded as \n in json to prevent it being interpreted as a new line.

    – Hugh
    Nov 14 '18 at 10:51














1












1








1









This question already has an answer here:




  • What is the difference between backticks (``) & double quotes (“”) in golang?

    3 answers




I have some strings that I'd like to convert to JSON. Using encoding/json here, haven't tried other packages.



The strings may contain newlines and other stuff that breaks JSON if saved as-is.



It works if I pass a string literal - it adds backslashes in front of backslashes. It doesn't work if I just pass a regular string. I can't seem to figure out if there is a way to use variables that contain string literals.



edit: as pointed out, these are not the same values and I kind of understand that, but it doesn't help me solve my problem.



The sample code:



package main

import (
"fmt"
"encoding/json"
)

func main() {
type Test struct {
Input string
}
regularString := Test{"asdnqwe"}
out, err := json.Marshal(regularString)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(out))

literalString := Test{`asdnqwe`}
out, err = json.Marshal(literalString )
if err != nil {
fmt.Println(err)
}
fmt.Println(string(out))
}









share|improve this question

















This question already has an answer here:




  • What is the difference between backticks (``) & double quotes (“”) in golang?

    3 answers




I have some strings that I'd like to convert to JSON. Using encoding/json here, haven't tried other packages.



The strings may contain newlines and other stuff that breaks JSON if saved as-is.



It works if I pass a string literal - it adds backslashes in front of backslashes. It doesn't work if I just pass a regular string. I can't seem to figure out if there is a way to use variables that contain string literals.



edit: as pointed out, these are not the same values and I kind of understand that, but it doesn't help me solve my problem.



The sample code:



package main

import (
"fmt"
"encoding/json"
)

func main() {
type Test struct {
Input string
}
regularString := Test{"asdnqwe"}
out, err := json.Marshal(regularString)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(out))

literalString := Test{`asdnqwe`}
out, err = json.Marshal(literalString )
if err != nil {
fmt.Println(err)
}
fmt.Println(string(out))
}




This question already has an answer here:




  • What is the difference between backticks (``) & double quotes (“”) in golang?

    3 answers








json string go string-literals






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 8:51







LauriK

















asked Nov 14 '18 at 8:35









LauriKLauriK

1,4971018




1,4971018




marked as duplicate by Flimzy, Volker go
Users with the  go badge can single-handedly close go questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 14 '18 at 8:54


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









marked as duplicate by Flimzy, Volker go
Users with the  go badge can single-handedly close go questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 14 '18 at 8:54


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.















  • What is the output you expect in your sample? If it makes it clearer, I've added a couple of extra Printlns that show the strings being encoded in the go playground here. Note the first has an actual new line, the second has a n which will be encoded as \n in json to prevent it being interpreted as a new line.

    – Hugh
    Nov 14 '18 at 10:51



















  • What is the output you expect in your sample? If it makes it clearer, I've added a couple of extra Printlns that show the strings being encoded in the go playground here. Note the first has an actual new line, the second has a n which will be encoded as \n in json to prevent it being interpreted as a new line.

    – Hugh
    Nov 14 '18 at 10:51

















What is the output you expect in your sample? If it makes it clearer, I've added a couple of extra Printlns that show the strings being encoded in the go playground here. Note the first has an actual new line, the second has a n which will be encoded as \n in json to prevent it being interpreted as a new line.

– Hugh
Nov 14 '18 at 10:51





What is the output you expect in your sample? If it makes it clearer, I've added a couple of extra Printlns that show the strings being encoded in the go playground here. Note the first has an actual new line, the second has a n which will be encoded as \n in json to prevent it being interpreted as a new line.

– Hugh
Nov 14 '18 at 10:51












1 Answer
1






active

oldest

votes


















2














The encoding/json properly encodes all string values.



Your first example works as you expect it because you use an interpreted string literal, and if that contains a n sequence, the compiler will replace that with a newline character.



Your second example doesn't work as you expect it because you used a raw string literal, which if contains a n sequence, that will not be replaced, but those 2 characters will remain in the string. And that will be escaped by encoding/json properly to remain that in the JSON outpupt.



So basically



"asdnqwe"`


and



`asdnqwe`


are 2 different strings, they are not equal, hence their JSON escaped values are also different.



Check Spec: String literals for more details.



Note that if you want to create a string value using a raw string literal, you can't use escape sequences in it. To have a newline in a raw string literal, simply break the line, like this:



s := `asd
qwe`


Another option is to "break" the string literal, and insert the newline using an interpreted string literal (and concatenate the parts):



s := `asd` + "n" + `qwe`





share|improve this answer


























  • Right, that makes sense.How can I make it work though?

    – LauriK
    Nov 14 '18 at 8:46











  • @LauriK: What's not working? You demonstrated that it works with ".

    – Flimzy
    Nov 14 '18 at 8:57











  • @LauriK Yes, it is working. If you want the string to contain a newline, use a string value that contains a newline and not a backslash followed by an n character.

    – icza
    Nov 14 '18 at 9:06






  • 1





    @LauriK Added examples how you can include newline in a raw string literal.

    – icza
    Nov 14 '18 at 9:22




















1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














The encoding/json properly encodes all string values.



Your first example works as you expect it because you use an interpreted string literal, and if that contains a n sequence, the compiler will replace that with a newline character.



Your second example doesn't work as you expect it because you used a raw string literal, which if contains a n sequence, that will not be replaced, but those 2 characters will remain in the string. And that will be escaped by encoding/json properly to remain that in the JSON outpupt.



So basically



"asdnqwe"`


and



`asdnqwe`


are 2 different strings, they are not equal, hence their JSON escaped values are also different.



Check Spec: String literals for more details.



Note that if you want to create a string value using a raw string literal, you can't use escape sequences in it. To have a newline in a raw string literal, simply break the line, like this:



s := `asd
qwe`


Another option is to "break" the string literal, and insert the newline using an interpreted string literal (and concatenate the parts):



s := `asd` + "n" + `qwe`





share|improve this answer


























  • Right, that makes sense.How can I make it work though?

    – LauriK
    Nov 14 '18 at 8:46











  • @LauriK: What's not working? You demonstrated that it works with ".

    – Flimzy
    Nov 14 '18 at 8:57











  • @LauriK Yes, it is working. If you want the string to contain a newline, use a string value that contains a newline and not a backslash followed by an n character.

    – icza
    Nov 14 '18 at 9:06






  • 1





    @LauriK Added examples how you can include newline in a raw string literal.

    – icza
    Nov 14 '18 at 9:22


















2














The encoding/json properly encodes all string values.



Your first example works as you expect it because you use an interpreted string literal, and if that contains a n sequence, the compiler will replace that with a newline character.



Your second example doesn't work as you expect it because you used a raw string literal, which if contains a n sequence, that will not be replaced, but those 2 characters will remain in the string. And that will be escaped by encoding/json properly to remain that in the JSON outpupt.



So basically



"asdnqwe"`


and



`asdnqwe`


are 2 different strings, they are not equal, hence their JSON escaped values are also different.



Check Spec: String literals for more details.



Note that if you want to create a string value using a raw string literal, you can't use escape sequences in it. To have a newline in a raw string literal, simply break the line, like this:



s := `asd
qwe`


Another option is to "break" the string literal, and insert the newline using an interpreted string literal (and concatenate the parts):



s := `asd` + "n" + `qwe`





share|improve this answer


























  • Right, that makes sense.How can I make it work though?

    – LauriK
    Nov 14 '18 at 8:46











  • @LauriK: What's not working? You demonstrated that it works with ".

    – Flimzy
    Nov 14 '18 at 8:57











  • @LauriK Yes, it is working. If you want the string to contain a newline, use a string value that contains a newline and not a backslash followed by an n character.

    – icza
    Nov 14 '18 at 9:06






  • 1





    @LauriK Added examples how you can include newline in a raw string literal.

    – icza
    Nov 14 '18 at 9:22
















2












2








2







The encoding/json properly encodes all string values.



Your first example works as you expect it because you use an interpreted string literal, and if that contains a n sequence, the compiler will replace that with a newline character.



Your second example doesn't work as you expect it because you used a raw string literal, which if contains a n sequence, that will not be replaced, but those 2 characters will remain in the string. And that will be escaped by encoding/json properly to remain that in the JSON outpupt.



So basically



"asdnqwe"`


and



`asdnqwe`


are 2 different strings, they are not equal, hence their JSON escaped values are also different.



Check Spec: String literals for more details.



Note that if you want to create a string value using a raw string literal, you can't use escape sequences in it. To have a newline in a raw string literal, simply break the line, like this:



s := `asd
qwe`


Another option is to "break" the string literal, and insert the newline using an interpreted string literal (and concatenate the parts):



s := `asd` + "n" + `qwe`





share|improve this answer















The encoding/json properly encodes all string values.



Your first example works as you expect it because you use an interpreted string literal, and if that contains a n sequence, the compiler will replace that with a newline character.



Your second example doesn't work as you expect it because you used a raw string literal, which if contains a n sequence, that will not be replaced, but those 2 characters will remain in the string. And that will be escaped by encoding/json properly to remain that in the JSON outpupt.



So basically



"asdnqwe"`


and



`asdnqwe`


are 2 different strings, they are not equal, hence their JSON escaped values are also different.



Check Spec: String literals for more details.



Note that if you want to create a string value using a raw string literal, you can't use escape sequences in it. To have a newline in a raw string literal, simply break the line, like this:



s := `asd
qwe`


Another option is to "break" the string literal, and insert the newline using an interpreted string literal (and concatenate the parts):



s := `asd` + "n" + `qwe`






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 14 '18 at 9:22

























answered Nov 14 '18 at 8:39









iczaicza

167k25332365




167k25332365













  • Right, that makes sense.How can I make it work though?

    – LauriK
    Nov 14 '18 at 8:46











  • @LauriK: What's not working? You demonstrated that it works with ".

    – Flimzy
    Nov 14 '18 at 8:57











  • @LauriK Yes, it is working. If you want the string to contain a newline, use a string value that contains a newline and not a backslash followed by an n character.

    – icza
    Nov 14 '18 at 9:06






  • 1





    @LauriK Added examples how you can include newline in a raw string literal.

    – icza
    Nov 14 '18 at 9:22





















  • Right, that makes sense.How can I make it work though?

    – LauriK
    Nov 14 '18 at 8:46











  • @LauriK: What's not working? You demonstrated that it works with ".

    – Flimzy
    Nov 14 '18 at 8:57











  • @LauriK Yes, it is working. If you want the string to contain a newline, use a string value that contains a newline and not a backslash followed by an n character.

    – icza
    Nov 14 '18 at 9:06






  • 1





    @LauriK Added examples how you can include newline in a raw string literal.

    – icza
    Nov 14 '18 at 9:22



















Right, that makes sense.How can I make it work though?

– LauriK
Nov 14 '18 at 8:46





Right, that makes sense.How can I make it work though?

– LauriK
Nov 14 '18 at 8:46













@LauriK: What's not working? You demonstrated that it works with ".

– Flimzy
Nov 14 '18 at 8:57





@LauriK: What's not working? You demonstrated that it works with ".

– Flimzy
Nov 14 '18 at 8:57













@LauriK Yes, it is working. If you want the string to contain a newline, use a string value that contains a newline and not a backslash followed by an n character.

– icza
Nov 14 '18 at 9:06





@LauriK Yes, it is working. If you want the string to contain a newline, use a string value that contains a newline and not a backslash followed by an n character.

– icza
Nov 14 '18 at 9:06




1




1





@LauriK Added examples how you can include newline in a raw string literal.

– icza
Nov 14 '18 at 9:22







@LauriK Added examples how you can include newline in a raw string literal.

– icza
Nov 14 '18 at 9:22





Popular posts from this blog

Bressuire

Vorschmack

Quarantine