JSON.parse throws syntax error when trying to parse escaped double quote

I can't seem to figure out Why this happens. I have an Array that I echo as a Json string into a dynamically created JavaScript tag in my page.

Here's the PHP code :

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

But when JavaScript is going to Parse the string, I get this Error:

SyntaxError: JSON.parse: expected ',' or '}' after property value in object at line 1 column 162 of the JSON data

This usually means that I have a Syntax error in my Json string, But I can't find this syntax error.

Here is what this script tag looks like in Browser:

<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>

For the sake of readability, I put a PRETTY_PRINT version of my Json string here:

{
"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"
}

As mentioned in the error, Column 162 of my Json data is the first occurrence of an escaped double quote (\"), But it there doesn't seem to be anything wrong with that!

Specially when PHP's own function (json_encode) gave me that!

What is the problem here?

(My browser is Firefox Quantum on Ubuntu Mate 16.04 ...)

1 answer

  • answered 2018-01-14 12:28 Lawrence Cherone

    When using json_encode, you don't need to escape anything, it will generate valid json. You also don't need to add it as a string and then parse it again with javascript.

    So for example you would do:

    <?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)
    );
    

    The result will look like:

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

    https://3v4l.org/qQunD