简体   繁体   中英

JSON.parse : Bad control character in string literal

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.

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM