简体   繁体   English

为什么json_encode后JSON.parse不起作用?

[英]Why doesn't JSON.parse after json_encode doesn't work?

Why won't this work for me? 为什么这对我不起作用?

<script>
JSON.parse(<?php echo json_encode(array('test123', 'test456')); ?>);
</script>

I get this error: 我收到此错误:

SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data

JSON is valid Javascript already, so JSON.parse is not needed here. JSON已经是有效的Javascript,所以这里不需要JSON.parse The following should work without a problem: 以下应该没有问题:

<script>
var obj = <?php echo json_encode(array('test123', 'test456')); ?>;
</script>

This will result in the following source on the page (which is perfectly valid JSON and Javascript): 这将导致页面上的以下源代码(这是完全有效的JSON和Javascript):

<script>
var obj = ["test123", "test456"];
</script>

Direct Answer : Since the above doesn't technically answer your question, JSON.parse is intended to work with strings. 直接答案 :由于上述技术上没有回答您的问题, JSON.parse旨在使用字符串。 You're not giving it a string, you're giving it an object (since, again, JSON is valid javascript). 你没有给它一个字符串,你给它一个对象(因为,再次,JSON是有效的javascript)。 JSON.parse should work fine, if you actually put the value in single quotes, but you'll need to make sure it's escaped properly (single quotes inside of single quotes will obviously cause problems). 如果您实际将值放在单引号中, JSON.parse应该可以正常工作,但是您需要确保它被正确转义(单引号内的单引号显然会导致问题)。 But I would avoid dealing with the JSON as a string, given that it's unnecessary in this case. 但我会避免将JSON作为字符串处理,因为在这种情况下它是不必要的。

PHP's json_encode produces a string, but it's an actual string in memory, not one in PHP syntax, so it's not wrapped in quotes when echo ed. PHP的json_encode生成一个字符串,但它是内存中的实际字符串,而不是PHP语法中的字符串,因此在echo ed时它不包含在引号中。 When echoed into the context of JavaScript code, it prints perfectly valid JSON, but the JS interpreter would not see it as a string because it's not wrapped in quotes. 当回显到JavaScript代码的上下文中时,它会打印出完全有效的JSON,但JS解释器不会将其视为字符串,因为它不包含在引号中。 Without them, JS sees an array denoted in literal syntax (because JSON borrows its own syntax from a subset of JS literal syntax). 没有它们,JS会看到一个用文字语法表示的数组(因为JSON从JS文字语法的子集中借用了自己的语法)。 Thus, trying to parse it would throw an error. 因此,尝试解析它会引发错误。

If your code ran, this is what would actually show up in a the outputted source: 如果你的代码运行了,这就是输出源中实际显示的内容:

<script>
var obj = ["test123", "test456"];
</script>

As obj now holds an array (which was denoted in JS literal syntax), running it through JSON.parse would cause an error. 由于obj现在拥有一个数组(用JS文字语法表示),通过JSON.parse运行它会导致错误。

Think of it like a sentence you wrote in a string in PHP, then echoed: 把它想象成你在PHP中用字符串写的句子,然后回应:

<?php
$sentence = 'I like beer.':
echo $sentence;
?>

This would produce the output: 这会产生输出:

I like beer.

Notice no wrapping quotes. 请注意没有包装报价。 Now, imagine writing a chunk of JSON "by hand" and echoing it: 现在,想象一下“手动”编写一大块JSON并回应它:

<?php
$json = '{"foo": "bar"}':
echo $json;
?>

This would output: 这将输出:

{"foo": "bar"}

Again, notice no wrapping quotes. 再次注意没有包装报价。 That assignment to the variable $json produces the same string data in PHP as your call to json_encode . 对变量$json赋值在PHP中生成与调用json_encode相同的字符串数据。 So echoing the output of your call also results in no quotes. 因此,回应您的通话输出也会导致没有报价。

Now, look at that last output chunk--what would a JavaScript engine do if it ran across something like that? 现在,看看最后一个输出块 - 如果遇到类似的事情,JavaScript引擎会怎么做?

So, to parse with JSON.parse , you need something JS will interpret as a string during the JS engine's parse. 因此,要使用JSON.parse进行解析,您需要JS在JS引擎的解析期间将其解释为字符串。 If you wrapped your PHP in single quotes as such: 如果您将PHP包装在单引号中:

<script>
var obj = '<?php echo json_encode(array('test123', 'test456')); ?>';
</script>

Then the output would be: 然后输出将是:

<script>
var obj = '["test123", "test456"]';
</script>

As this is a string in proper format, it is now JSON and could be passed to JSON.parse . 由于这是一个格式正确的字符串,现在它是JSON,可以传递给JSON.parse

( Note: Simply wrapping in single quotes isn't safe, though, as the structure which PHP encoded may have a string within which contains a single quote. That would result in a syntax error in your JavaScript.) 注意:简单地用单引号括起来并不安全,因为PHP编码的结构可能包含一个包含单引号的字符串。这会导致JavaScript中出现语法错误。)

As has been mentioned, none of this is necessary anyway--you can hand JS your non-quoted JSON and skip the parse because the JS interpreter will parse it as is and save you a step. 正如已经提到的那样,无论如何都不需要这样做 - 你可以将JS提交给非引用的JSON并跳过解析,因为JS解释器将按原样解析它并为您节省一步。 I just wanted you to understand the mechanics. 我只是想让你了解这些机制。 Hope I didn't confuse you... :( 希望我没有混淆你...... :(

JavaScript is the only language in which the direct output of JSON into a context which makes it no longer a string could actually produce something workable. JavaScript是唯一一种将JSON直接输出到上下文中的语言,这使得它不再是一个字符串,实际上可以生成一些可行的东西。 This is because JSON syntax borrows from a subset of the JavaScript literal syntax. 这是因为JSON语法借用了JavaScript文字语法的一个子集。

Context is everything in this. 语境就是这一切。 For example, sending JSON to JavaScript over AJAX is different than the context you showed for trying to give JavaScript some JSON. 例如,通过AJAX将JSON发送到JavaScript与您尝试向JavaScript提供一些JSON时显示的上下文不同。 In the case of AJAX, the response from the server to the AJAX code is a JS string in memory already. 在AJAX的情况下,服务器对AJAX代码的响应已经是内存中的JS字符串。 Whereas having PHP echo into JS code produces syntax for parsing by the JS engine, thus needing quotes to make it a string. 而将PHP回显到JS代码中会产生JS引擎解析的语法,因此需要引号使其成为字符串。

I think you have to put the PHP output between quotes "" 我认为你必须把PHP输出放在引号之间“”

Try this: 尝试这个:

<script>
    JSON.parse("<?php echo json_encode(array('test123', 'test456')); ?>");
</script>

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

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