1. Hey! Guest! The 35th GMC Jam will take place between November 28th, 12:00 UTC - December 2nd, 12:00 UTC. Why not join in! Click here to find out more!
    Dismiss Notice

[SOLVED] JSON encoding and newlines.

Discussion in 'Programming' started by Noman, May 26, 2017.

  1. Noman

    Noman Member

    Joined:
    Dec 10, 2016
    Posts:
    10
    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);
     
  2. zbox

    zbox Member GMC Elder

    Joined:
    Jun 21, 2016
    Posts:
    796
    try this:
    Code:
    var nL = chr($D) + chr($A);
    
    stringToSend = "line one" + nL + "line two";
    
     
  3. Noman

    Noman Member

    Joined:
    Dec 10, 2016
    Posts:
    10
    Worked like a champ, zbox. Thanks.

    (convoluted... but functioning!)
     
  4. zbox

    zbox Member GMC Elder

    Joined:
    Jun 21, 2016
    Posts:
    796
    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");
    
     
  5. elementbound

    elementbound Member

    Joined:
    Jun 30, 2016
    Posts:
    114
    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)
     
  6. zbox

    zbox Member GMC Elder

    Joined:
    Jun 21, 2016
    Posts:
    796
    you need both 0x0d and 0x0a for it to be a valid linebreak, not just 0xa :)
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice