php json_encode & jquery parseJSON 单引号问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17926354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
php json_encode & jquery parseJSON single quote issue
提问by revo
I searched and read most of the related topics, but they weren't what I was looking for.
我搜索并阅读了大部分相关主题,但它们并不是我想要的。
I've a JSON enocded string with json_encode
PHP function:
我有一个带有json_encode
PHP 函数的 JSON 编码字符串:
{"casts":["Matthew Modine","Adam Baldwin","Vincent D'Onofrio"],"year":1987}
I'm working with jQuery to put the values in appropriate fields too, in the case of testing I did the below:
我正在使用 jQuery 将值也放在适当的字段中,在测试的情况下,我执行了以下操作:
<script>
var obj = jQuery.parseJSON('<?=$data?>');
console.log(obj);
</script>
Suppose that $data is this:
假设 $data 是这样的:
$data =
<<<END
{"casts":["Matthew Modine","Adam Baldwin","Vincent D'Onofrio"],"year":1987}
END;
What Google chrome console produces in this case:
在这种情况下,谷歌浏览器控制台会产生什么:
Uncaught SyntaxError: Unexpected identifier
However when I make a change in JSON encoded string - adding Backslashto single quote :
但是,当我对 JSON 编码的字符串进行更改时 - 将反斜杠添加到单引号中:
{"casts":["Matthew Modine","Adam Baldwin","Vincent D\'Onofrio"],"year":1987}
Console output is as normal:
控制台输出正常:
Object {casts: Array[3], year: 1987}
casts: Array[3]
year: 1987
The question: is this error in console expected? I think escaping or replacing '
with \'
will be so dirty!
问题:控制台中的这个错误是预期的吗?我想逃避或更换'
有\'
会这么脏!
UPDATED
更新
Actually $datavalue comes from a json_encode($var)
and $var is an array!
实际上$data值来自 ajson_encode($var)
而 $var 是一个数组!
$data = json_encode($var);
采纳答案by Quentin
However when I make a change in JSON encoded string - adding Backslash to single quote
但是,当我对 JSON 编码的字符串进行更改时 - 将反斜杠添加到单引号
That escapes it in the PHP string literal. It is then inserted into the PHP string as a simple '
.
在 PHP 字符串文字中转义它。然后将它作为一个简单的'
.
If you want to escape it before inserting it into JavaScript then you need to add slashes to the string you get outof json_encode
(or rather, since you aren't using that (you should be!) the JSON string you build by hand).
如果你想将其插入JavaScript的前逃脱它,那么你需要斜线添加到字符串你出来的json_encode
(或者说,因为你不使用你建立的手说(你应该!)JSON字符串)。
That is more work then you need though. The real solution is to remember that JSON is a subset of JavaScript literal syntax:
不过,这比您需要的工作还要多。真正的解决方案是记住 JSON 是 JavaScript 文字语法的一个子集:
var obj = <?=$data?>;
回答by seanvalencourt
For the broader problem of passing a JSON-encoded string in PHP (e.g., through cURL), using the JSON_HEX_APOS option is the cleanest way to solve this problem. This would solve your problem as well, although the previous answers are correct that you don't needto call parseJSON, and the JavaScript object is the same without calling parseJSON on $data
.
对于在 PHP 中传递 JSON 编码字符串的更广泛的问题(例如,通过 cURL),使用 JSON_HEX_APOS 选项是解决这个问题的最干净的方法。这也可以解决您的问题,尽管前面的答案是正确的,您不需要调用 parseJSON,并且 JavaScript 对象是相同的,而无需在 上调用 parseJSON $data
。
For your code, you would just make this change:
对于您的代码,您只需进行以下更改:
json_encode($var)
to json_encode($var, JSON_HEX_APOS)
.
json_encode($var)
到json_encode($var, JSON_HEX_APOS)
。
Here's an example of the correctly encoded data being parsed by jQuery: http://jsfiddle.net/SuttX/
以下是 jQuery 解析正确编码数据的示例:http: //jsfiddle.net/SuttX/
For further reading, here's an example from the PHP.net json_encode manual entryExample #2:
如需进一步阅读,请参阅PHP.net json_encode 手册条目Example #2 中的一个示例:
$a = array('<foo>',"'bar'",'"baz"','&blong&', "\xc3\xa9");
echo "Apos: ", json_encode($a, JSON_HEX_APOS), "\n";
This will output:
这将输出:
Apos: ["<foo>","\u0027bar\u0027","\"baz\"","&blong&","\u00e9"]
A full list of JSON constants can be found here: PHP.net JSON constants
可以在此处找到 JSON 常量的完整列表:PHP.net JSON 常量
回答by Orangepill
The issue you are facing is that you are presenting the results of the json_encode
call to JavaScript as a string whereas it is valid JavaScript. Remove the jQuery.jsonParse
set out of the output and simply assign the echoed results to the JavaScript variable in question.
您面临的问题是您json_encode
将 JavaScript 调用的结果显示为字符串,而它是有效的 JavaScript。从jQuery.jsonParse
输出中删除set 并简单地将回显的结果分配给相关的 JavaScript 变量。
var obj = <?= json_encode(array("casts"=>array(
"Matthew Modine","Adam Baldwin","Vincent D'Onofrio"
),"year"=>1987)); ?>;
回答by hsuk
This should be straightforward if the issue is about single quote only:
如果问题仅与单引号有关,这应该很简单:
str_replace("'", "\'", json_encode($array));
回答by Mujahid khan
check out its really help me
看看它真的对我有帮助
$products_arr=array();
$products_arr["category"]=array();
while ($row = $cats->fetch(PDO::FETCH_ASSOC)){
$product_item=array(
"id" => $row['id'],
"title" => json_encode($row['title'])// these will help you
);
array_push($products_arr["category"], $product_item);
}
echo json_encode($products_arr);