0

I'm trying to parse the following string to JSON and it does not seem to work due to the ampersand character \&\#38. It throws an error on JSON.parse: SyntaxError: Unexpected token & at Object.parse (native)

{"pluginType":"cite","reference":{"title":"Mixed-Initiative Real-Time Topic Modeling \&\#38; Visualization for Crisis Counseling","url":"http://doi.acm.org/10.1145/2678025.2701395","pages":"417--426","year":"2015","publisher":"ACM","_id":"56d59ced7eb2323d008fab24","label":"Dinakar2015MRT26780252701395"}}

Can this be escaped somehow? It seems like valid input for a user.

2
  • 1
    JSON.parse('{"pluginType":"cite","reference":{"title":"Mixed-Initiative Real-Time Topic Modeling \&\#38; Visualization for Crisis Counseling","url":"http://doi.acm.org/10.1145/2678025.2701395","pages":"417--426","year":"2015","publisher":"ACM","_id":"56d59ced7eb2323d008fab24","label":"Dinakar2015MRT26780252701395"}}') parses fine for me. Commented Apr 5, 2016 at 20:25
  • 1
    @thomas That's because JS converts the literal '\&' into the string &. Try JSON.parse(String.raw`"\&"`) instead. Commented Apr 5, 2016 at 20:35

1 Answer 1

1

An escaping \ can't precede &.


(source: json.org)

If you wanted to escape &, just use & (there is no need to escape it).

document.write(JSON.parse(String.raw`"&"`));

If you wanted the string \&, you need to escape the \ like \\&.

document.write(JSON.parse(String.raw`"\\&"`));

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

2 Comments

Thank you! This is semi-automatically generated so I can't really prevent that from being inputted, but I want to not crash on it. Is there a javascript function that will escape characters like that properly? What are the other characters except & that I would need to escape?
You must not escape & in JSON. Clarify if you wanted & or \&.

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.