Home > OS >  JSON.parse : Bad control character in string literal
JSON.parse : Bad control character in string literal

Time:12-27

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 "asdfadf\tadfadf", but when try parse it, it's shown error. eg. code:

let s = '{"adf":"asdf\tasdfdaf"}';
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.

CodePudding user response:

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": "asdf\tasdfdaf" };

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.

CodePudding user response:

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

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

  • Related