Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Valid JSON gives error while parsing - Uncaught SyntaxError: Unexpected token S

Tags:

json

parsing

I have a valid JSON string as below:- DEMO

[
   {
      "field":"Name",
      "rules":[
         {
            "Regex":"\\S",
            "ValidationMessage":" Name cannot be blank."
         },
         {
            "Regex":"^.{1,50}$",
            "ValidationMessage":"Length should not exceeds 50 characters."
         }
      ]
   },
   {
      "field":"Abbreviation",
      "rules":[
         {
            "Regex":"\\S",
            "ValidationMessage":" Abbreviation cannot be blank."
         },
         {
            "Regex":"^.{1,15}$",
            "ValidationMessage":"Length should not exceeds 15 characters."
         }
      ]
   },
   {
      "field":"PhoneNumber",
      "rules":[
         {
            "Regex":"\\S",
            "ValidationMessage":"Phone Number cannot be blank."
         },
         {
            "Regex":"^\\d{10}$",
            "ValidationMessage":"Length must be 10 digits"
         }
      ]
   },
   {
      "field":"SelectedCampus",
      "rules":[
         {
            "Regex":"\\S",
            "ValidationMessage":"Please st Serviced Campus"
         }
      ]
   }
]

When I do JSON.parse it is throwing error as :-

Uncaught SyntaxError: Unexpected token S 
like image 827
Shubh Avatar asked Jun 25 '26 20:06

Shubh


1 Answers

Posting my comment as an answer: you will need to double escape your JSON string, before you can parse it with JSON.parse(..).

Let's take a string like, say, \\S. It consists of two characters: '\\', 'S'.

JSON.parse("...\\S...") sees that as a back-slash, and expects one of 'n', 'r', 't' (or other escape characters) after it. It neither expects S or a d. Hence you get that error.

To solve, you will need to double escape the JSON String. Like: \\\\S & \\\\d.

like image 150
UltraInstinct Avatar answered Jun 27 '26 13:06

UltraInstinct



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!