0

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.

4
  • 1
    See e.g. stackoverflow.com/q/19573525 Commented Dec 26, 2022 at 15:40
  • Does this answer your question? bad control character error in json parse Commented Dec 26, 2022 at 15:44
  • @jonrsharpe That answers are not cleared Commented Dec 27, 2022 at 7:09
  • @RobertMoskal The answers are short, not cleared the reason. Commented Dec 27, 2022 at 7:10

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

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

1 Comment

It would be nice to give a brief explanation of how this works / how it solves the problem, and how it's different than existing answers.
0

I'd like to make mention of the useful "jsonrepair" npm library. It solves a number of issues with unparsable JSON, including control characters as presented in this issue:

import { jsonrepair } from 'jsonrepair';

let s = '{"adf":"asdf\tasdfdaf"}';
JSON.parse(jsonrepair(s));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.