Search code examples
javascriptjqueryajaxjsonspecial-characters

looking for js library for formatting string to match json requirments


I'm using jQuery ajax to send updates from the client's browser to my server,
I noticed that there is some characters that JSON doesn't support,
and in order to send them, i need to add additional \ in front of each.

This characters are well documented at json.com:

jsonStrings
(source: json.org)

I'm not so good at javascripting (i'm new in this area),
So i wonder if there is any already made function that takes a string and formats it to fit this requirement?

iv'e searched the web but couldn't find any javascript solution for this..

Thanks in advance, Eitan.


Solution

  • Solved! i spent too much time on this @$!

    I found that the JSON.stringify indeed take care of the special characters.
    The problem was in the way that i used to structure the data...
    I did it like:

    blah = JSON.stringify( { a: "1" } );
    $.ajax({
             type: "POST",
             url: "page.aspx/MethodName",
             data: "{ paramName: '" + blah + "'}",
             contentType: "application/json; charset=utf-8",
             dataType: "json"});
    

    To fix this, i just did:

    //nesting the param name in the data structure passed to stringify:
    blah = JSON.stringify( { paramName : { a: "1" } } ); 
        $.ajax({
                 type: "POST",
                 url: "page.aspx/MethodName",
                 data: blah,
                 contentType: "application/json; charset=utf-8",
                 dataType: "json"});
    

    Thanks for everyone who tried to help me solve this..