如何处理json字符串php中的反斜杠 [英] How to deal with backslashes in json strings php

查看:192
本文介绍了如何处理json字符串php中的反斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试解码json_encode生成的字符串时,json_encode和/或json_decode似乎有些奇怪:

There appears to be an oddity with json_encode and/or json_decode when attempting decode a string that was produced by json_encode:

    $object = new stdClass;
    $object->namespace = 'myCompany\package\subpackage';

    $jsonEncodedString = json_encode($object);
    echo $jsonEncodedString;
    // Result of echo being:
    // {"namespace":"myCompany\\package\\subpackage"}

    $anotherObject = json_decode($jsonEncodedString);
    echo $anotherObject->namespace;
    // Result of echo being:
    // myCompany\package\subpackage


    $yetAnotherObject = json_decode('{"namespace":"myCompany\\package\\subpackage"}');
    // Result should be:
    // myCompany\package\subpackage
    // But returns an invalid string sequence error instead...
    echo json_last_error_msg();

在此之前,我从未遇到过问题,因为直到今天,我再也不需要捕获其中带有反斜杠的字符串.在查看上面的代码时,我可以使用PHP的内置组件进行编码/解码.但是,如果我尝试解码此编码器产生的字符串,则会收到错误消息.我已经阅读了诸如"预定义常量之类的文档项目"和其他堆栈问题,例如"如何删除反斜杠(使用php的json响应中的"\")?".但是我似乎找不到原因为什么无法解码json_encode生成的字符串.我用于测试此代码的PHP版本是5.5.9.

I've never experienced a problem previous to this, as I've never had to capture a string with backslashes in it until today. In reviewing the code above, I can encode/decode utilizing PHP's built in components. However if I attempt to decode a string that was produced by this encoder I get an error message. I've read in documentation items like "Predefined Constants" and other stack questions like "how remove the backslash ("\") in the json response using php?". But I can't seem to find a reason WHY I can't decode a string that was produced by json_encode. The PHP version I'm using to test this code is 5.5.9.

我知道丢失某些东西可能完全一无所知,但是如果我尝试在其他地方使用它,我是否应该以不同的方式处理由json_encode生成的字符串?

I know I could be totally clueless by missing something, but should I be handling my string that was produced by json_encode differently if I attempt to use it elsewhere?

推荐答案

答案在以下问题中:

$jsonEncodedString = json_encode($object);
echo $jsonEncodedString;
// Result of echo being:
// {"namespace":"myCompany\\package\\subpackage"}

您不必去除任何斜杠.相反.您必须将echo-ed文本表示为PHP源代码.

You don't have to strip any slashes. On the contrary. You have to express the echo-ed text as PHP source code.

$yetAnotherObject = json_decode('{"namespace":"myCompany\\\\package\\\\subpackage"}');

反斜杠(\)是PHP和JSON中的特殊字符.两种语言都使用它来转义字符串中的特殊字符,并且为了正确地在字符串中表示反斜杠,必须在PHP和JSON中都给它加上另一个反斜杠.

The backslash (\) is a special character in both PHP and JSON. Both languages use it to escape special characters in strings and in order to represent a backslash correctly in strings you have to prepend another backslash to it, both in PHP and JSON.

让我们尝试对上面的字符串执行PHP解析器的工作.在开放括号之后,它会遇到一个字符串用单引号.在单引号字符串中需要转义两个特殊字符:撇号(')和反斜杠(\).尽管撇号总是需要转义,但是PHP解释器是宽容的,并且允许不转义的反斜杠,只要它们不会造成混淆即可.但是,在单引号引起来的字符串中反斜杠的正确表示形式是\\.

Let's try to do the job of the PHP parser on the string above. After the open parenthesis it encounters a string enclosed in single quotes. There are two special characters that needs escaping in single quote strings: the apostrophe (') and the backslash (\). While the apostrophe always needs escaping, the PHP interpreter is forgiving and allows unescaped backslashes as long as they do not create confusion. However, the correct representation of the backslash inside single quoted strings is \\.

传递给函数json_decode()的字符串是

{"namespace":"myCompany\\package\\subpackage"}

请注意,这是在运行时处理的字符的准确列表,而不是用PHP或任何其他语言表示的字符串.这些语言具有表示特殊字符的特殊规则.这只是纯文本.

Please note that this is the exact list of characters processed on runtime and not a string represented in PHP or any other language. The languages have special rules for representing special characters. This is just plain text.

上面的文本由函数json_decode()解释,它希望它是JSON的一部分. JSON是一种小语言,它具有用于编码字符串中特殊字符的特殊规则.反斜杠是这些字符之一,当它出现在字符串中时,必须在其前面加上另一个反斜杠. JSON不能原谅;遇到反斜杠时,始终将其视为字符串中下一个字符的转义字符.

The text above is interpreted by function json_decode() that expects it to be a piece of JSON. JSON is a small language, it has special rules for encoding of special characters in strings. The backslash is one of these characters and when it appears in a string it must be prepended by another backslash. JSON is not forgiving; when it encounters a backslash it always treats it as an escape character for the next character in the string.

json_decode()创建的对象,在成功解析JSON表示后,您将它们传递给它,包含一个名为namespace的单个属性,其值为:

The object created by json_decode() after successful parsing of the JSON representation you pass them contains a single property named namespace whose value is:

myCompany\package\subpackage

再次请注意,这是实际的字符串,而不是任何语言的表示形式.

Note again that this is the actual string of characters and not a representation in any language.

返回您的代码:

$yetAnotherObject = json_decode('{"namespace":"myCompany\\package\\subpackage"}');

PHP解析器使用PHP规则解释上述代码.它了解到json_decode()函数必须以文本{"namespace":"myCompany\package\subpackage"}作为参数来调用.

The PHP parser interprets the code above using the PHP rules. It understands that the json_decode() function must be invoked with the text {"namespace":"myCompany\package\subpackage"} as argument.

json_decode()使用其规则,并尝试将上面的文本解释为JSON表示形式. myCompany之前的引号(")表示必须将"myCompany\package\subpackage"解析为字符串. package之前的反斜杠被解释为p的转义字符,但是\p对于JSON中的字符串不是有效的转义序列.这就是为什么它拒绝继续并返回NULL的原因.

json_decode() uses its rules and tries to interpret the text above as a piece of JSON representation. The quote (") before myCompany tells it that "myCompany\package\subpackage" must be parsed as string. The backslash before package is interpreted as an escape character for p but \p is not a valid escape sequence for strings in JSON. This is why it refuses to continue and returns NULL.

这篇关于如何处理json字符串php中的反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆