简体   繁体   English

JSON - 在JavaScript中解码字符串的正确方法

[英]JSON - proper way to decode string in JavaScript

I'm wondering what would be the best way to decode JSON string inside Javascript code. 我想知道在Javascript代码中解码JSON字符串的最佳方法是什么。

I want my json string to be embeded inside my JS, like this: 我希望我的json字符串嵌入我的JS中,如下所示:

var params = dojo.fromJson('<?=json_encode($this->params); ?>');

dojo.fromJson decodes my string and json_encode is a php function that encodes an object on the server side. dojo.fromJson解码我的字符串,json_encode是一个php函数,它编码服务器端的对象。

It seems that json encoder ignores ' chars and only converts " to \\". 似乎json编码器忽略'chars并且仅转换为'“。 So when one of my variables inside $this->params contains a ' character there is a Javascript error. 因此,当$ this-> params中的一个变量包含'字符时,就会出现Javascript错误。

For example: 例如:

var params = dojo.fromJson('{"id":"11","object_type":"Let's go"}');

What is the best way to approach this ? 解决这个问题的最佳方法是什么?

Thanks for help. 感谢帮助。

Since you are producing the JSON yourself, you can trust it, so you don't need to treat it as JSON and can treat it as JS instead. 由于您自己生成JSON,因此您可以信任它,因此您不需要将其视为JSON,而是可以将其视为JS。

var params = <?=json_encode($this->params); ?>;

PHP's JSON encoder will escape </script> for you so you don't need to worry about terminating your script element with your data. PHP的JSON编码器将为您转义</script> ,因此您无需担心使用数据终止脚本元素。

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

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