QNimate

  • CoursesVideos
  • WP PremiumPlugins
  • DemosLab
  • Bitcoin BankingBuy, Sell, Store and Earn Interest
  • 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
    4 years ago

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

    ReplyCancel
  2. Gajapathi
    5 years ago

    Thanks for this lovely post

    ReplyCancel
  3. Gajapathi
    5 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 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`.

Narayan Prusty

I am a full-stack web developer. I specialize in Blockchain and JavaScript. This is my personal blog where I write about programming and technologies that I learn and feel interesting to share.

5 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 Arrays in HTML5 localStorage
  • How to Store Objects in HTML5 localStorage
  • Stop requestAnimationFrame
Our Sponsor
Freelance: I am available
@narayanprusty
Hi, I am a full-stack developer - focusing on JavaScript, WordPress, Blockchain, DevOps, Serverless and Cordova. You can outsource your app development to me.





Will get back to you soon!!!
WordPress
ReactJS
Meteor
Blockchain
Serverless
Kubernetes
DevOps
DB & Storage
Ejabberd
Let's get started
My Books

2014 - 2015 © QNimate
All tutorials MIT license