QNimate

  • CoursesVideos
  • WP PremiumPlugins
  • DemosLab
  • Home
  • QIdea
  • QTrack
Home Carbon Ads JSON.parse() throws “unexpected token” error for valid JSON

JSON.parse() throws “unexpected token” error for valid JSON

Although your JSON string is valid JSON.parse is likely to throw error. This is because JSON.parse cannot parse some special characters that are \n, \t, \r and \f.

You need to escape these special characters for before passing JSON string to JSON.parse function.

Here is a function that takes a JSON string and escapes the special characters:

        function escapeSpecialChars(jsonString) {

            return jsonString.replace(/\n/g, "\\n")
                .replace(/\r/g, "\\r")
                .replace(/\t/g, "\\t")
                .replace(/\f/g, "\\f");

        }
Sep 11, 2015Narayan Prusty
Best Photo Straightening Online ToolGenerate Unique Number in JavaScript
Comments: 3
  1. Tyler Collier
    6 years ago

    Don’t forget about \", as mentioned on this stackoverflow answer.

    ReplyCancel
  2. Gajapathi
    6 years ago

    Thanks for this lovely post

    ReplyCancel
  3. Gajapathi
    6 years ago

    Very Helpful, after wasting my 2 hrs of time, i found this, and ended my serach for JSON.parse error

    ReplyCancel

Leave a Reply to Gajapathi Cancel reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Narayan Prusty

I am a software engineer specialising in Blockchain, DevOps and Go/JavaScript. This is my personal blog where I write about things that I learn and feel interesting to share.

7 years ago 3 Comments Web Development
Share this
0
GooglePlus
0
Facebook
0
Twitter
0
Linkedin
Related Articles
  • JavaScript Promise vs Callback
  • Python like Multiline Strings In JavaScript
  • How to Store Objects in HTML5 localStorage
  • How to Store Arrays in HTML5 localStorage
  • Stop requestAnimationFrame
Our Sponsor
My Books

2014 - 2015 © QNimate
All tutorials MIT license