Php Json String, Escape Double Quotes for Js Output

PHP json_encode data with double quotes

json_encode already takes care of this, you are breaking the result by calling stripslashes:

echo json_encode($data); //properly formed json

PHP JSON String escape Double Quotes inside value?

Since yesterday I was trying to solve this tricky problem, and after a lot of hair pulling I came up with this solution.

First let us clarify our assumptions.

  • json string should be right formated.
  • The keys and values are quoted with double quotation.

Analyzing the problem:

We know that json keys formated like this (,"keyString":) and json value is (:"valueString",)

keyString: is any sequence of characters except (:").

valueString: is any sequence of characters except (",).

Our goal is to escape quotations inside valueString, to achive that we need to separate keyStrings and valueStrings.

  • But we have also a valid json format like this ("keyString":digit,) this will cause a problem because it breaks out assumption that says values always ended with (",)
  • Another problem is having empty values like ("keyString":" ")

Now after analyzing the problem we can say

  1. json keyString has (,") before it and (":) after it.
  2. json valueString can have (:") before and (",) after OR
    (:) before and digit as a value then (,) after OR
    (:) followed by (" ") then (,)

The solution:
Using this facts the code will be

function escapeJsonValues($json_str){
$patern = '~(?:,\s*"((?:.(?!"\s*:))+.)"\s*(?=\:))(?:\:\s*(?:(\d+)|("\s*")|(?:"((?!\s*")(?:.(?!"\s*,))+.)")))~';
//remove { }
$json_str = rtrim(trim(trim($json_str),'{'),'}');
if(strlen($json_str)<5) {
//not valid json string;
return null;
}
//put , at the start nad the end of the string
$json_str = ($json_str[strlen($json_str)-1] ===',') ?','.$json_str :','.$json_str.',';
//strip all new lines from the string
$json_str=preg_replace('~[\r\n\t]~','',$json_str);

preg_match_all($patern, $json_str, $matches);
$json='{';
for($i=0;$i<count($matches[0]);$i++){

$json.='"'.$matches[1][$i].'":';
//value is digit
if(strlen($matches[2][$i])>0){
$json.=$matches[2][$i].',';
}
//no value
elseif (strlen($matches[3][$i])>0) {
$json.='"",';
}
//text, and now we can see if there is quotations it will be related to the text not json
//so we can add slashes safely
//also foreword slashes should be escaped
else{
$json.='"'.str_replace(['\\','"' ],['/','\"'],$matches[4][$i]).'",';
}
}
return trim(rtrim($json,','),',').'}';
}

Note: The code realizes white spaces.

Will php's json_encode() always use double quotes as string delimiter?

Yes, as defined in the JSON spec, the delimiter will always be ". However, values may contain ' characters, which would break your HTML. To keep it simple and not worry about what might or mightn't pose an issue, HTML-escape your values!

<section data-settings="<?= htmlspecialchars(json_encode($foo)); ?>"></section>

This is guaranteed to work, always, no matter what values you pipe in or how you encode them.

NOTE that htmlspecialchars will by default only encode ", not '; so you must use " as the delimiter in HTML (or change the default escaping behavior).

How to escape double quotes in JSON

Try this:

"maingame": {
"day1": {
"text1": "Tag 1",
"text2": "Heute startet unsere Rundreise \" Example text\". Jeden Tag wird ein neues Reiseziel angesteuert bis wir.</strong> "
}
}

(just one backslash (\) in front of quotes).

Escaping quotes in a javascript object generated from PHP

My attempts to edit @kmoser's answer with the actual solution that worked were rejected in peer review, so here's what worked. All credit to @kmoser:

$json_feedback = preg_replace( preg_quote('/\u/'), '\\\\\\\\u', json_encode( $feedback, JSON_HEX_APOS | JSON_HEX_QUOT ) );

It works by replacing singles and double quotes with hex strings when the data is retrieved from the MySQL database. For reasons I don't understand, that still broke the javascript, so I then did a preg_replace to put an additional backslash before the escaped code.

Notice how many backslashes I had to put in to persuade the preg_replace to put in the additional backslash to prevent the javascript breaking. I may be able to get away with fewer backslashes, the number that appears here is mostly out of sheer frustration with this silly issue!

Replace double quotes with single quotes in json string in php

I hope this works as expected ([^{,:])"(?![},:])

$json='{"en":"<b class="test" size="5" >Description</b>"}';
$json=preg_replace('/([^{,:])"(?![},:])/', "$1".'\''."$2",$json);

Results in

{"en":"<b class='test' size='5' >Description</b>"}

PHP Add double quotes before and after variable in json string

OK, if you're new to all this, maybe regular expressions aren't the best answer.

You can also use a simple str_replace function (doc) like this :

str_replace(array('file:', 'label:'),array('"file":', '"label":'),$your_json_string);

To exploit the json in php, you'll need to decode it using json_decode, and use a loop to check the label values (I advise a foreach loop).



Related Topics



Leave a reply



Submit