[SOLVED] JSON encoding and newlines.

N

Noman

Guest
So, trying to send a string to slack with some newlines in thar... and having trouble formatting the string correctly.

\n comes out as \\n in the string... I've tried separating it out as a character with single and double quotes... it always gives me more \\'s than I need and they are in the string.

The one thing that works is just hitting Enter in the code editor... which results in a properly single \... with an extra character. It ends up as \r\n ... which works fine for slack but results in horribly unreadable code.

What's the right way to put a newline in a string for JSON?

Here's a bit that ends with \\n's and doesn't work at all.

var slackreport, str;
slackreport = ds_map_create();
ds_map_add(slackreport, "text", "thing \n thing");
str = json_encode(slackreport);
get[0] = http_post_string("http:/stuff", str);
 

zbox

Member
GMC Elder
try this:
Code:
var nL = chr($D) + chr($A);

stringToSend = "line one" + nL + "line two";
 
N

Noman

Guest
Worked like a champ, zbox. Thanks.

(convoluted... but functioning!)
 

zbox

Member
GMC Elder
All good! Maybe for readabilitys sake you could do something like this
Code:
///string_concat_nl(string[,string,...])
var nL = chr($D) + chr($A), s = argument[0], i;

for (i=1; i < argument_count; ++i) {
    s += nL + argument[i];
}

return s;
and then you can do things like
Code:
var stringMsg = string_concat_nl("line one", "line two", "line three");
 
E

elementbound

Guest
To add a bit of background info: Game Maker doesn't do any character escaping, using # only works for drawing new lines.
If you are absolutely sure that you will not have \n's in your input ( not newlines but a backslash and an n ), you could just use string_replace and replace all \n's with chr(10)
 
Top