skip to Main Content

I think this is a basic question, but I can’t understand the reason. in JSON, it’s valid to has a special character like "asdfadftadfadf", but when try parse it, it’s shown error.
eg. code:

let s = '{"adf":"asdftasdfdaf"}';
JSON.parse(s);

Error:

Uncaught SyntaxError: Bad control character in string literal in JSON at position 12
    at JSON.parse (<anonymous>)
    at <anonymous>:1:6

I need to understand what is the issue, and solution.

2

Answers


  1. You have to take into account that t will be involved in two parsing operations: first, when your string constant is parsed by JavaScript, and second, when you parse the JSON string with JSON.parse(). Thus you must use

    let s = '{"adf":"asdf\tasdfdaf"}';
    

    If you don’t, you’ll get the error you’re seeing from the actual tab character embedded in the string. JSON does not allow "control" characters to be embedded in strings.

    Also, if the actual JSON content is being created in server-side code somehow, it’s probably easier to skip building a string that you’re immediately going to parse as JSON. Instead, have your code build a JavaScript object initializer directly:

    let s = { "adf": "asdftasdfdaf" };
    

    In your server environment there is likely to be a JSON tool that will allow you to take a data structure from PHP or Java or whatever and transform that to JSON, which will also work as JavaScript syntax.

    Login or Signup to reply.
  2. let t = '{"adf":"asdf\tasdfdaf"}';
    

    var obj = JSON.parse(t)
    console.log(obj)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search