尝试解析转义双引号时,JSON.parse会引发语法错误

时间:2018-01-14 12:15:03

标签: javascript php json parsing

我似乎无法弄清楚为什么会这样。我有一个数组,我作为一个Json字符串回显到我的页面中动态创建的JavaScript标记。

这是PHP代码:

echo '<script type="text/javascript">var Lang = \'';
echo str_replace('\'', '\\\'', json_encode($this->Lang));
echo '\';Lang = JSON.parse(Lang);</script>';

但是当JavaScript要解析字符串时,我会收到此错误:

  

SyntaxError:JSON.parse:在属性值之后预期','或'}'   JSON数据的第1行第162列的对象

这通常意味着我的Json字符串中有一个语法错误,但是我找不到这种语法错误。

以下是此脚本标记在浏览器中的样子:

<script type="text/javascript">var Lang = '{"Code":"en","Layout":"LtR","Error_NoPassword":"Password is Required","Error_NoUsername":"Username is Required","Header_Notification_Comment":"[A] commented on \"[O]\"","Header_Notification_Follow":"[A] is now following \"[O]\"","Header_Notification_Like":"[A] liked \"[O]\"","Header_Notification_Message":"[A] sent you a message.","PLogin_Login_Fail":"Login failed","PLogin_Login_ForgotLink":"Click here if you forgot your password !","PLogin_Multiverse_Description_Text":"Multiverse is an application developed for Story writers of Comics, Games, Movies, Novels and etc. This application uses \"Snowflake Method\" to make things easier for the author.","PLogin_Multiverse_Description_Title":"What is Multiverse ?","PLogin_ResetPassword_Title":"Reset Password","PLogin_ResetPassword_Description":"Enter the email address you use on Multiverse. Your email must have been verified after you signed up. If you didn\'t verify your email address, We\'re afraid there\'s nothing we can do at this point.","PLogin_ResetPassword_MailSent":"In case you have entered your email address correctly, And it is verified, Then an email was sent to your address containing a single-use link to reset your password.","PLogin_SrcError_Account":"In order to have an account of your own, You need to sign up first !","PLogin_SrcError_Edit":"In order to create your own content, You need to create an account first !","PLogin_SrcError_People":"In order to interact with other people on Multiverse, You need to create an account first !","PLogin_Signup_UsernameWillBe":"Your username will be : ","Signup_Fail_Captcha":"Captcha Failed !","Signup_Fail_Email":"Incorrect email address","Signup_Fail_Password":"It is recommended for password to be 8 or more characters","Signup_Fail_Unknown":"Registration failed for unknown reason","Signup_Fail_UsernameTaken":"Username is already taken","Signup_Fail_UsernameInvalid":"Username is Invalid.","Signup_Fail_Realname":"Enter your Name","Signup_Title":"Become an Author now","Signup_ExploreButton":"Explore as Guest !","UniExp_Info_IsPublic":"Public","UniExp_Info_Description":"Description","UniExp_Info_Language":"Language","UniExp_SelectedInfo_NoTimeline":"No Timeline Selected","UniExp_SelectedInfo_NoStory":"No Story Selected","Word_Account":"Account","Word_Act":"Act","Word_Character":"Character","Word_ContactUs":"Contact Us","Word_Editors":"Editors","Word_EmailAddress":"Email Address","Word_Explore":"Explore","Word_ID":"ID","Word_License":"License","Word_Login":"Log In","Word_Logout":"Sign Out","Word_MobileVersion":"Mobile Version","Word_MyUniverses":"My Universes","Word_Name":"Name","Word_No":"No","Word_Owner":"Owner","Word_Part":"Part","Word_Password":"Password","Word_People":"People","Word_Plot":"Plot","Word_Realname":"Real Name","Word_Scene":"Scene","Word_Search":"Search","Word_Select":"Select","Word_Signup":"Sign up","Word_Story":"Story","Word_Timeline":"Timeline","Word_Unknown":"Unknown","Word_Universe":"Universe","Word_Username":"Username","Word_You":"You","Word_Yes":"Yes"}';Lang = JSON.parse(Lang);</script>

为了便于阅读,我在这里放了一个PRETTY_PRINT版本的Json字符串:

{
"Code": "en",
"Layout": "LtR",
"Error_NoPassword": "Password is Required",
"Error_NoUsername": "Username is Required",
"Header_Notification_Comment": "[A] commented on \"[O]\"",
"Header_Notification_Follow": "[A] is now following \"[O]\"",
"Header_Notification_Like": "[A] liked \"[O]\"",
"Header_Notification_Message": "[A] sent you a message.",
"PLogin_Login_Fail": "Login failed",
"PLogin_Login_ForgotLink": "Click here if you forgot your password !",
"PLogin_Multiverse_Description_Text": "Multiverse is an application developed for Story writers of Comics, Games, Movies, Novels and etc. This application uses \"Snowflake Method\" to make things easier for the author.",
"PLogin_Multiverse_Description_Title": "What is Multiverse ?",
"PLogin_ResetPassword_Title": "Reset Password",
"PLogin_ResetPassword_Description": "Enter the email address you use on Multiverse. Your email must have been verified after you signed up. If you didn\'t verify your email address, We\'re afraid there\'s nothing we can do at this point.",
"PLogin_ResetPassword_MailSent": "In case you have entered your email address correctly, And it is verified, Then an email was sent to your address containing a single-use link to reset your password.",
"PLogin_SrcError_Account": "In order to have an account of your own, You need to sign up first !",
"PLogin_SrcError_Edit": "In order to create your own content, You need to create an account first !",
"PLogin_SrcError_People": "In order to interact with other people on Multiverse, You need to create an account first !",
"PLogin_Signup_UsernameWillBe": "Your username will be : ",
"Signup_Fail_Captcha": "Captcha Failed !",
"Signup_Fail_Email": "Incorrect email address",
"Signup_Fail_Password": "It is recommended for password to be 8 or more characters",
"Signup_Fail_Unknown": "Registration failed for unknown reason",
"Signup_Fail_UsernameTaken": "Username is already taken",
"Signup_Fail_UsernameInvalid": "Username is Invalid.",
"Signup_Fail_Realname": "Enter your Name",
"Signup_Title": "Become an Author now",
"Signup_ExploreButton": "Explore as Guest !",
"UniExp_Info_IsPublic": "Public",
"UniExp_Info_Description": "Description",
"UniExp_Info_Language": "Language",
"UniExp_SelectedInfo_NoTimeline": "No Timeline Selected",
"UniExp_SelectedInfo_NoStory": "No Story Selected",
"Word_Account": "Account",
"Word_Act": "Act",
"Word_Character": "Character",
"Word_ContactUs": "Contact Us",
"Word_Editors": "Editors",
"Word_EmailAddress": "Email Address",
"Word_Explore": "Explore",
"Word_ID": "ID",
"Word_License": "License",
"Word_Login": "Log In",
"Word_Logout": "Sign Out",
"Word_MobileVersion": "Mobile Version",
"Word_MyUniverses": "My Universes",
"Word_Name": "Name",
"Word_No": "No",
"Word_Owner": "Owner",
"Word_Part": "Part",
"Word_Password": "Password",
"Word_People": "People",
"Word_Plot": "Plot",
"Word_Realname": "Real Name",
"Word_Scene": "Scene",
"Word_Search": "Search",
"Word_Select": "Select",
"Word_Signup": "Sign up",
"Word_Story": "Story",
"Word_Timeline": "Timeline",
"Word_Unknown": "Unknown",
"Word_Universe": "Universe",
"Word_Username": "Username",
"Word_You": "You",
"Word_Yes": "Yes"
}

正如错误中所提到的,我的Json数据的第162列是第一次出现的转义双引号(\“),但它似乎没有任何问题!

特别是PHP自己的函数(json_encode)给了我那个!

这里有什么问题?

(我的浏览器是Ubuntu Mate 16.04上的Firefox Quantum ...)

2 个答案:

答案 0 :(得分:2)

使用json_encode时,你不需要逃避任何事情,它会生成有效的json。您也不需要将其添加为字符串,然后使用javascript再次解析它。

例如,您可以这样做:

<?php
// a mock of your object
$_this = new class {
    public $Code = 'en';
};

echo sprintf(
    '<script type="text/javascript">var Lang=%s;</script>', 
    json_encode($_this)
);

结果如下:

<script type="text/javascript">var Lang={"Code":"en"};</script>

https://3v4l.org/qQunD

答案 1 :(得分:0)

编辑: Lawrence Cherone的答案更好!

找到答案...
逃脱的双引号是用HTML写的,所以它是一个\#34;在HTML中但是HTML将它用于Javascript并且Javascript消耗了反斜杠 因此,在Javascript中,它是一个没有反斜杠的双引号(如&#34;)。但JSon需要反斜杠来解释&#34;作为价值的一部分。

解决方案:
我在PHP中添加了另一个 str_replace 并将所有我的(\&#34;)字符串替换为(\\&#34;),以便它最终为JSon提供一个额外的反斜杠。

新的(正确的)PHP:

    echo '<script type="text/javascript">var Lang = \'';
    $JSN = str_replace('\'', '\\\'', json_encode($this->Lang));
    $JSN = str_replace('\"', '\\\"',$JSN);
    echo $JSN;
    echo '\';Lang = JSON.parse(Lang);</script>';