0

The following conversion fails saying bad control character

var myObj = JSON.parse('{"imagePath": "http://somedomain.com/test.jpg?path=\728\1.jpg"}');
console.log(myObj);

is that because of the following characters "\" in the image path , if so do we have any solution for this?

If i remove that character it works.

Thanks.

5
  • 1
    I'm not entirely sure how this makes sense, but if you escape it with \\\ it works. JSON.parse('{"imagePath": "http://somedomain.com/test.jpg?path=\\\\728\\\\1.jpg"}') why wouldn't just 1 be enough? Commented Mar 6, 2013 at 18:44
  • I am getting data that file , when i convert string to object it fails Commented Mar 6, 2013 at 18:45
  • No i understand what you are doing, i don't understand why changing it to path=\\728\\1.jpg isn't working for me. Commented Mar 6, 2013 at 18:46
  • stackoverflow.com/questions/3807537/… Commented Mar 6, 2013 at 18:47
  • I am also getting the same error after escaping also Commented Mar 6, 2013 at 18:48

2 Answers 2

1

You need to escape the \ character whereever you are generating the JSON.

If it is a literal, then you have to escape the escapes also:

j = JSON.parse('{"imagePath": "http://somedomain.com/test.jpg?path=\\\\728\\\\1.jpg"}');
Sign up to request clarification or add additional context in comments.

5 Comments

Honestly the best solution, if you have influence over whatever is consuming this imagePath, is to use forward slashes in your paths and avoid this head-ache.
I will let the service team know
how can i replace single "\" with four
If you are typing the string literal in "by hand" in your code, you need to type in 4 `. That's what I meant by *If it is a literal*. If you are getting the string as data, perhaps from an input field, then you should not be calling JSON.parse` on it. It all just works. If you are receiving the string from the server in a JSON packet, then the server should be using a JSON serializer that serializes the string correctly.
Here's a jsFiddle showing you only need to do the escapes when you are actually typing the string into your JavaScript code: jsfiddle.net/bman654/5dv7s
1

\ is an escape character. So if you want to use \ in your image Path string, then you need to double escape it. i.e. use \\

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.