0

This is the string in question:

var string = "{\"CMD\":\"<a href=\"someurl.com\">link</a>\"}";

When I un-escape the quotes (except the url) and validate, it appears to be valid:

{
    "CMD": "<a href=\"someurl.com\">link</a>"
}

But it breaks my Javascript program.

edit: Have also tried double escaping. The first double quote seems to get escaped, but not the second:

{
        "CMD": "<a href=\\"someurl.com\\">link</a>"
}

Offending code:

webSocket.send("{\"CMD\":\"<a href=\\\"link.com\\\">link</a>\"}");
5
  • Convert double quotes to single inside the string { "CMD": "<a href=\'someurl.com\'>link</a>" } Commented Jul 31, 2015 at 11:58
  • Wouldn't the \"someurl.com\" be unescaped as well? So you need to double escape them? Maybe? Commented Jul 31, 2015 at 11:58
  • 1
    try : var string = "{\"CMD\":\"<a href=\\\"someurl.com\\\">link</a>\"}"; Commented Jul 31, 2015 at 11:58
  • 1
    Why is this an issue? You shouldn't be creating JSON strings by hand, you should use a library function for it, and it will almost surely get it right. Commented Jul 31, 2015 at 12:01
  • 1
    Simply use JSON.stringify and JSON.parse. Commented Jul 31, 2015 at 12:03

3 Answers 3

4

Why not use single ' as below

{
    "CMD": "<a href='someurl.com'>link</a>"
}

' is equivalent to " for quoting HTML attribute values. This way JSONLint validates it.

These two HTMLs are equivalent/same.

<a href='someurl.com'>link</a>

<a href="someurl.com">link</a>
Sign up to request clarification or add additional context in comments.

4 Comments

The question is about the string, not the object.
"' is equivalent to " in javascript" While true (well, almost), it's irrelevant in the above. The relevant thing to the above is that ' is valid for quoting HTML attribute values.
This is the only thing that worked - double escaping and triple escaping double quotes didn't work.
@crm: This would also work: "{\"CMD\":\"<a href=\\\"someurl.com\\\">link</a>\"}" (proof), but the above is much simpler.
0

The href attribute has additional ". You need to double escape it:

"{\"CMD\":\"<a href=\\\"someurl.com\\\">link</a>\"}"

7 Comments

This nor double escaping works in Javascript for me.
Well, post your code. JSON.parse("{\"CMD\":\"<a href=\\\"someurl.com\\\">link</a>\"}"); works for me.
webSocket.send("{\"CMD\":\"<a href=\\\"link.com\\\">link</a>\"}");
What do you do with the string after that? JSON.parse on it will work, sending it should work as well, because it is simply a string.
It is sent to a Java server where it is parsed as a JSONObject: JSONObject json = new JSONObject(stringJson);
|
0

Change like this :

{ "CMD": "<a href=\"someurl.com\">link</a>" }

1 Comment

Could you be more descriptive?

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.