escaping special characters in JSON

J

James Black

I have an application that relies on JSON, and I realized yesterday
that I when the user types at least some of these characters (most
likely all, haven't had time to verify) that the parser has problems:
, { } [ ] " '

How can I escape these characters so that it is in the file, but can
still be parsed?

For example:
{data: ["I want a quote, 'and so here it is', [with something in
brackets]'", "and {more data}"]}

I also had a problem when a newline ('\n') was entered, so I turn those
into '<br>'.

Thanx for any help.
 
M

Martin Honnen

James said:
I have an application that relies on JSON, and I realized yesterday
that I when the user types at least some of these characters (most
likely all, haven't had time to verify) that the parser has problems:
, { } [ ] " '

How can I escape these characters so that it is in the file, but can
still be parsed?

The JSON libraries should do all escaping for your, for instance for
JavaScript <http://www.json.org/js.html> there is the JSON.stringify
function which should do all escaping.
And if you want to create JSON with other programming languages then
there are libraries as well.

Note that brackets [] and {} inside of string literals do not need to be
escaped.
 
J

James Black

Thank you for the response.

I am not using the stringify function, so I will try using that on
Monday and see if the problem goes away.
 
D

Douglas Crockford

James said:
I have an application that relies on JSON, and I realized yesterday
that I when the user types at least some of these characters (most
likely all, haven't had time to verify) that the parser has problems:
, { } [ ] " '

How can I escape these characters so that it is in the file, but can
still be parsed?

For example:
{data: ["I want a quote, 'and so here it is', [with something in
brackets]'", "and {more data}"]}

Of the characters in the set

, { } [ ] " '

the only one requiring escapement is the ". This can be done by giving it a \
prefix.

http://JSON.org/
 
J

James Black

Thank you. On Monday I will try these ideas.

I find JSON to be the best way for my Ajax application to transfer
data, but I am still getting used to it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top