Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

apostrophe in json object to add slash [duplicate]

Tags:

json

jquery

I am getting a json object like this

{
    "First": "MyName's",
     "Last": "MyLast"
}

I want to stringify this object so that 's in value become \' it could be 's or 'S or 'anything

I am using JSON.stringify(json_obj) but its giving me string

"{"First":"MyName's","Last":"MyLast"}"

you can see MyName's I want this to MyName\'s

like image 205
coure2011 Avatar asked Oct 04 '12 14:10

coure2011


2 Answers

Try using a regex replace incase if you going to have more than once such values,

.stringify(data).replace(/'/g, "\\'")

DEMO: http://jsfiddle.net/qMsyg/2/

like image 63
Selvakumar Arumugam Avatar answered Nov 02 '22 23:11

Selvakumar Arumugam


after you've stringified the json just apply a replace("'", "\'");

JSON.stringify(json).replace("'", "\'");

Or you may use a replacer parameter into stringify() method

JSON.stringify(json, function(key, value) {
   return value.replace("'", "\'");
})

NOTE: replace("'", "\'") will only replace the first occurrence, as pointed out by @vega. If you have more values to escape use a regular expression (like replace(/'/g, "\\'")).

Choose the one which best fits your needs

like image 29
Fabrizio Calderan Avatar answered Nov 02 '22 23:11

Fabrizio Calderan