简体   繁体   English

带单引号和双引号的 JSON.parse 字符串?

[英]JSON.parse string with single and double quotes?

I am saving an array as json and parsing it again upon load.我将数组保存为 json 并在加载时再次解析它。 However, after adding HTML with both single and double quotes, this has stopped working.但是,在添加带有单引号和双引号的 HTML 后,这已停止工作。

How can I escape the quotes?我怎样才能逃避引号?

JSON.parse('[["",null,null,null,null,null,"","","<span onclick=insertRow()><i class='fa fa-plus-circle fa-lg'></i></span>"]]');

uncaught SyntaxError: missing ) after argument list

EDIT:编辑:

My string is saved in database using JSON.stringify.我的字符串使用 JSON.stringify 保存在数据库中。 It ends up in the following format:它以以下格式结束:

[["ad",null,true,false,true,false,"","","<span onclick=insertRow()><i class='fa fa-plus-circle fa-lg'></i></span>"]]

when Im loading it again, I do it like follows:当我再次加载它时,我会这样做:

var phpsave = JSON.parse('<?php echo $result->save; ?>');

If im escaping the single quotes before saving, the escaping just dissappears upon loading..如果我在保存前转义单引号,则在加载时转义就会消失。

You're dynamically producing Javascript source code.您正在动态生成 Javascript 源代码。 You need to ensure that what you're producing is syntactically valid.您需要确保您生成的内容在语法上是有效的。 The easiest way to produce valid Javascript literals from PHP is using json_encode :从 PHP 生成有效 Javascript 文字的最简单方法是使用json_encode

var phpsave = JSON.parse(<?php echo json_encode($result->save); ?>);
// look ma, no quotes!   ^                                       ^

But wait, aren't you passing JSON to your Javascript?但是等等,您不是将JSON传递给您的 Javascript 吗? Isn't JSON already valid Javascript? JSON 不是已经有效的 Javascript 吗? Why, yes, yes it is.为什么,是的,是的。 So you can leave out that step:所以你可以省略这一步:

var phpsave = <?php echo $result->save; ?>;

Of course, you might want to ensure that you're really passing valid JSON here first before you start outputting random Javascript code.当然,你可能想确保你真的通过有效的JSON这里首先你开始输出随机Javascript代码之前。

你可以像

 var r = JSON.parse('[["",null,null,null,null,null,"","","<span onclick=insertRow()><i class=\'fa fa- plus - circle fa- lg\'></i></span>"]]');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM