159

When creating JSON data manually, how should I escape string fields? Should I use something like Apache Commons Lang's StringEscapeUtilities.escapeHtml, StringEscapeUtilities.escapeXml, or should I use java.net.URLEncoder?

The problem is that when I use SEU.escapeHtml, it doesn't escape quotes and when I wrap the whole string in a pair of 's, a malformed JSON will be generated.

vela
  • 147
  • 10
βξhrαng
  • 41,698
  • 21
  • 103
  • 145
  • 22
    If you're wrapping the whole string in a pair of `'`, you're doomed from the start: JSON strings can only be surrounded with `"`. See http://www.ietf.org/rfc/rfc4627.txt. – Thanatos Jun 11 '10 at 04:01
  • 2
    +1 for the `StringEscapeUtilities` outline. Its pretty useful. – Muhammad Gelbana Nov 05 '12 at 13:33

18 Answers18

166

Ideally, find a JSON library in your language that you can feed some appropriate data structure to, and let it worry about how to escape things. It'll keep you much saner. If for whatever reason you don't have a library in your language, you don't want to use one (I wouldn't suggest this¹), or you're writing a JSON library, read on.

Escape it according to the RFC. JSON is pretty liberal: The only characters you must escape are \, ", and control codes (anything less than U+0020).

This structure of escaping is specific to JSON. You'll need a JSON specific function. All of the escapes can be written as \uXXXX where XXXX is the UTF-16 code unit¹ for that character. There are a few shortcuts, such as \\, which work as well. (And they result in a smaller and clearer output.)

For full details, see the RFC.

¹JSON's escaping is built on JS, so it uses \uXXXX, where XXXX is a UTF-16 code unit. For code points outside the BMP, this means encoding surrogate pairs, which can get a bit hairy. (Or, you can just output the character directly, since JSON's encoded for is Unicode text, and allows these particular characters.)

Thanatos
  • 37,926
  • 14
  • 76
  • 136
  • Is it valid in JSON, like in JavaScript, to enclose strings in double quotes or single quotes? Or is it only valid to enclose them in double quotes? – βξhrαng Jun 11 '10 at 04:53
  • 3
    @Sergei: The characters `{[]}:?` must not be escaped with a single backslash. (`\:`, for example, is not valid in a JSON string.) All of those can optionally be escaped using the `\uXXXX` syntax, at the waste of several bytes. See §2.5 of the RFC. – Thanatos Jan 08 '14 at 22:11
  • 2
    I'm not sure how widely it's supported, but in my experience a call to `JSON.stringify()` did the job. – Mr. Lance E Sloan Jan 30 '14 at 19:15
  • For my tiny brain, the RFC is a bit vague, when it states "... any UNICODE character...". Which encoding? utf-8, utf-16, shift-jis, ...? Big endian/little endian? The RFC also does not state the character encoding for the whole json string. Some clarification would be much appreciated. Maybe for Java programmers, the term "unicode" is enough to ring a bell, but for C/C++ programmers having a std::string etc, it is not enough information. – BitTickler Mar 02 '16 at 19:44
  • @BitTickler: I'm not sure which part of the RFC you're referencing. If you mean what Unicode characters are valid in a string literal, then the production `unescaped` tells you what characters you can include without an escape sequence, and which must be escaped; when those two are combined, a string literal can contain any sequence of Unicode code points. String literals have no encoding: they are text. The JSON value as a whole (including embedded literals), however, *might*, if it needs to be stored as bytes; the standard mandates one of the UTF- encodings shall be used. – Thanatos Mar 29 '16 at 07:01
  • @LS. stringify() can change the order of non-array object properties, as cited at https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify – Patanjali Jun 13 '16 at 07:27
  • @Patanjali: The question and comments didn't specify order is important. Usually, order **_should not_** be important. From json.org: "An object is an unordered set of name/value pairs." If order is important to the consumer of JSON, it should be written in a way to preserve that order. For example, use property keys that would fall into the correct order when sorted. – Mr. Lance E Sloan Jun 13 '16 at 13:28
  • @LS. Faerie's nuts. (Fair enough). – Patanjali Jun 14 '16 at 15:39
  • 2
    @BitTickler a unicode character is not vague at all -- it just means that it has a code point (or points) in the unicode spec. When you use std::string, it is a bunch of unicode characters. When you need to serialize it, lets say to a file or across the network, that's where 'which encoding' comes in. It seems according to Thanatos that they want you to use a UTF, but technically any encoding can be used as long as it can be reconstituted into unicode characters. – Gerard ONeill Jul 20 '17 at 15:54
56

Extract From Jettison:

 public static String quote(String string) {
         if (string == null || string.length() == 0) {
             return "\"\"";
         }

         char         c = 0;
         int          i;
         int          len = string.length();
         StringBuilder sb = new StringBuilder(len + 4);
         String       t;

         sb.append('"');
         for (i = 0; i < len; i += 1) {
             c = string.charAt(i);
             switch (c) {
             case '\\':
             case '"':
                 sb.append('\\');
                 sb.append(c);
                 break;
             case '/':
 //                if (b == '<') {
                     sb.append('\\');
 //                }
                 sb.append(c);
                 break;
             case '\b':
                 sb.append("\\b");
                 break;
             case '\t':
                 sb.append("\\t");
                 break;
             case '\n':
                 sb.append("\\n");
                 break;
             case '\f':
                 sb.append("\\f");
                 break;
             case '\r':
                sb.append("\\r");
                break;
             default:
                 if (c < ' ') {
                     t = "000" + Integer.toHexString(c);
                     sb.append("\\u" + t.substring(t.length() - 4));
                 } else {
                     sb.append(c);
                 }
             }
         }
         sb.append('"');
         return sb.toString();
     }
MonoThreaded
  • 9,824
  • 9
  • 63
  • 98
  • 10
    Well, this was the OP tag – MonoThreaded Jun 19 '16 at 01:21
  • Don't understand only when c < ' ', change to \u. In my case, there is character \uD38D, which is 55357 and over ' ', so doesn't change to \u... – Stony Nov 30 '16 at 06:38
  • 1
    @Stony Sounds like a new question – MonoThreaded Dec 05 '16 at 20:48
  • @MonoThreaded Thanks for your reply, I still don't know why. but finally, I changed the method to fix it like below, if (c < ' ' || c > 0x7f) { t = "000" + Integer.toHexString(c).toUpperCase(); sb.append("\\u" + t.substring(t.length() - 4)); } else { sb.append(c); } } – Stony Dec 06 '16 at 01:47
  • 1
    @Stony, all characters other than `"`, `\ `, and control characters (those before “ ”) are valid inside JSON strings as long as the output encoding matches. In other words, you do not need to encode “펍” as `\uD38D` as long as the UTF encoding is preserved. – meustrus Apr 20 '18 at 17:14
37

Try this org.codehaus.jettison.json.JSONObject.quote("your string").

Download it here: http://mvnrepository.com/artifact/org.codehaus.jettison/jettison

Stephan
  • 37,597
  • 55
  • 216
  • 310
dpetruha
  • 1,064
  • 10
  • 11
24

org.json.simple.JSONObject.escape() escapes quotes,\, /, \r, \n, \b, \f, \t and other control characters. It can be used to escape JavaScript codes.

import org.json.simple.JSONObject;
String test =  JSONObject.escape("your string");
Dan-Dev
  • 7,171
  • 3
  • 31
  • 45
  • 3
    It depends on the json library you are using (JSONObject.escape, JSONObject.quote, ..) but it's always a static method doing the quoting job and simply should be reused – amine Apr 03 '14 at 11:12
  • Which library is org.json part of? I don't have it on my classpath. – Alex Spurling Feb 22 '18 at 12:08
  • com.googlecode.json-simple see https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1.1 – Dan-Dev Oct 21 '20 at 20:02
22

Apache commons lang now supports this. Just make sure you have a recent enough version of Apache commons lang on your classpath. You'll need version 3.2+

Release Notes for version 3.2

LANG-797: Added escape/unescapeJson to StringEscapeUtils.

CloudNinja
  • 1,346
  • 1
  • 17
  • 30
  • This is the most practical answer for me. Most projects already use apache commons lang, so no need to add a dependency for one function. A JSON builder would probably be the best answer. – absmiths Jun 28 '17 at 13:59
  • As a follow-up, and because I can't figure out how to edit a comment I added a new one, I found javax.json.JsonObjectBuilder and javax.json.JsonWriter. Very nice builder/writer combination. – absmiths Jun 28 '17 at 14:27
  • 1
    This is deprecated in apache commons lang, you need to use apache commons **text**. Sadly, this library follows the optional/outdated spec by escaping `/` characters. This breaks lots of things including JSON with URLs in it. The original proposal had `/` as a special char to escape but this is no longer the case, as we can see in [the latest spec at time of writing](http://www.ecma-international.org/ecma-262/8.0/index.html) – adamnfish Mar 27 '18 at 15:32
10

org.json.JSONObject quote(String data) method does the job

import org.json.JSONObject;
String jsonEncodedString = JSONObject.quote(data);

Extract from the documentation:

Encodes data as a JSON string. This applies quotes and any necessary character escaping. [...] Null will be interpreted as an empty string

I.G. Pascual
  • 5,192
  • 5
  • 36
  • 53
5

StringEscapeUtils.escapeJavaScript / StringEscapeUtils.escapeEcmaScript should do the trick too.

Syon
  • 6,625
  • 5
  • 33
  • 40
5

If you are using fastexml jackson, you can use the following: com.fasterxml.jackson.core.io.JsonStringEncoder.getInstance().quoteAsString(input)

If you are using codehaus jackson, you can use the following: org.codehaus.jackson.io.JsonStringEncoder.getInstance().quoteAsString(input)

Dhiraj
  • 542
  • 6
  • 14
3

Not sure what you mean by "creating json manually", but you can use something like gson (http://code.google.com/p/google-gson/), and that would transform your HashMap, Array, String, etc, to a JSON value. I recommend going with a framework for this.

Vladimir
  • 2,236
  • 3
  • 24
  • 39
  • 2
    By manually I meant not by using a JSON library like Simple JSON, Gson, or XStream. – βξhrαng Jun 11 '10 at 04:56
  • Just a matter of curiosity -- why wouldn't you want to use one of these APIs? It's like trying to escape URLs manually, instead of using URLEncode/Decode... – Vladimir Jun 11 '10 at 14:40
  • 1
    Not really the same, those libraries come with a lot more than the equivalent of URLEncode/Decode, they include a whole serialization package to allow persistence of java object in json form,and sometimes your really only need to encode a short bunch of text – jmd Dec 12 '11 at 10:08
  • 2
    do a manual creating of JSON makes sense, if you wish to not include a library just for serializing small bits of data – Aditya Kumar Pandey Mar 03 '12 at 12:07
  • 2
    I would ask to have a team member removed from any project I was on if they dared to create JSON manually where there existed a high quality library to do so. – Michael Joyce Nov 14 '13 at 01:37
2

I have not spent the time to make 100% certain, but it worked for my inputs enough to be accepted by online JSON validators:

org.apache.velocity.tools.generic.EscapeTool.EscapeTool().java("input")

although it does not look any better than org.codehaus.jettison.json.JSONObject.quote("your string")

I simply use velocity tools in my project already - my "manual JSON" building was within a velocity template

EdChum
  • 294,303
  • 173
  • 671
  • 486
Tjunkie
  • 491
  • 4
  • 6
2

For those who came here looking for a command-line solution, like me, cURL's --data-urlencode works fine:

curl -G -v -s --data-urlencode 'query={"type" : "/music/artist"}' 'https://www.googleapis.com/freebase/v1/mqlread'

sends

GET /freebase/v1/mqlread?query=%7B%22type%22%20%3A%20%22%2Fmusic%2Fartist%22%7D HTTP/1.1

, for example. Larger JSON data can be put in a file and you'd use the @ syntax to specify a file to slurp in the to-be-escaped data from. For example, if

$ cat 1.json 
{
  "type": "/music/artist",
  "name": "The Police",
  "album": []
}

you'd use

curl -G -v -s --data-urlencode query@1.json 'https://www.googleapis.com/freebase/v1/mqlread'

And now, this is also a tutorial on how to query Freebase from the command line :-)

vijucat
  • 1,979
  • 1
  • 14
  • 16
2

Use EscapeUtils class in commons lang API.

EscapeUtils.escapeJavaScript("Your JSON string");
theJ
  • 970
  • 3
  • 12
  • 22
  • 1
    Note that single quotes for example are handled differently when escaping to javascript or json. In commons.lang 3.4 StringEscapeUtils (https://commons.apache.org/proper/commons-lang/javadocs/api-3.4/org/apache/commons/lang3/StringEscapeUtils.html#escapeJson(java.lang.String)) has a escapeJSON method which is different than the escapeJavaScript method in commons.lang 2: https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html#escapeJavaScript(java.lang.String) – GlennV Mar 23 '16 at 15:42
1

Consider Moshi's JsonWriter class. It has a wonderful API and it reduces copying to a minimum, everything can be nicely streamed to a filed, OutputStream, etc.

OutputStream os = ...;
JsonWriter json = new JsonWriter(Okio.buffer(Okio.sink(os)));
json.beginObject();
json.name("id").value(getId());
json.name("scores");
json.beginArray();
for (Double score : getScores()) {
  json.value(score);
}
json.endArray();
json.endObject();

If you want the string in hand:

Buffer b = new Buffer(); // okio.Buffer
JsonWriter writer = new JsonWriter(b);
//...
String jsonString = b.readUtf8();
orip
  • 66,082
  • 20
  • 111
  • 144
1

If you need to escape JSON inside JSON string, use org.json.JSONObject.quote("your json string that needs to be escaped") seem to work well

webjockey
  • 1,159
  • 2
  • 15
  • 24
1

Apache commons-text now has a StringEscapeUtils.escapeJson(String).

Mohsen
  • 3,412
  • 3
  • 31
  • 58
0

The methods here that show the actual implementation are all faulty.
I don't have Java code, but just for the record, you could easily convert this C#-code:

Courtesy of the mono-project @ https://github.com/mono/mono/blob/master/mcs/class/System.Web/System.Web/HttpUtility.cs

public static string JavaScriptStringEncode(string value, bool addDoubleQuotes)
{
    if (string.IsNullOrEmpty(value))
        return addDoubleQuotes ? "\"\"" : string.Empty;

    int len = value.Length;
    bool needEncode = false;
    char c;
    for (int i = 0; i < len; i++)
    {
        c = value[i];

        if (c >= 0 && c <= 31 || c == 34 || c == 39 || c == 60 || c == 62 || c == 92)
        {
            needEncode = true;
            break;
        }
    }

    if (!needEncode)
        return addDoubleQuotes ? "\"" + value + "\"" : value;

    var sb = new System.Text.StringBuilder();
    if (addDoubleQuotes)
        sb.Append('"');

    for (int i = 0; i < len; i++)
    {
        c = value[i];
        if (c >= 0 && c <= 7 || c == 11 || c >= 14 && c <= 31 || c == 39 || c == 60 || c == 62)
            sb.AppendFormat("\\u{0:x4}", (int)c);
        else switch ((int)c)
            {
                case 8:
                    sb.Append("\\b");
                    break;

                case 9:
                    sb.Append("\\t");
                    break;

                case 10:
                    sb.Append("\\n");
                    break;

                case 12:
                    sb.Append("\\f");
                    break;

                case 13:
                    sb.Append("\\r");
                    break;

                case 34:
                    sb.Append("\\\"");
                    break;

                case 92:
                    sb.Append("\\\\");
                    break;

                default:
                    sb.Append(c);
                    break;
            }
    }

    if (addDoubleQuotes)
        sb.Append('"');

    return sb.ToString();
}

This can be compacted into

    // https://github.com/mono/mono/blob/master/mcs/class/System.Json/System.Json/JsonValue.cs
public class SimpleJSON
{

    private static  bool NeedEscape(string src, int i)
    {
        char c = src[i];
        return c < 32 || c == '"' || c == '\\'
            // Broken lead surrogate
            || (c >= '\uD800' && c <= '\uDBFF' &&
                (i == src.Length - 1 || src[i + 1] < '\uDC00' || src[i + 1] > '\uDFFF'))
            // Broken tail surrogate
            || (c >= '\uDC00' && c <= '\uDFFF' &&
                (i == 0 || src[i - 1] < '\uD800' || src[i - 1] > '\uDBFF'))
            // To produce valid JavaScript
            || c == '\u2028' || c == '\u2029'
            // Escape "</" for <script> tags
            || (c == '/' && i > 0 && src[i - 1] == '<');
    }



    public static string EscapeString(string src)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        int start = 0;
        for (int i = 0; i < src.Length; i++)
            if (NeedEscape(src, i))
            {
                sb.Append(src, start, i - start);
                switch (src[i])
                {
                    case '\b': sb.Append("\\b"); break;
                    case '\f': sb.Append("\\f"); break;
                    case '\n': sb.Append("\\n"); break;
                    case '\r': sb.Append("\\r"); break;
                    case '\t': sb.Append("\\t"); break;
                    case '\"': sb.Append("\\\""); break;
                    case '\\': sb.Append("\\\\"); break;
                    case '/': sb.Append("\\/"); break;
                    default:
                        sb.Append("\\u");
                        sb.Append(((int)src[i]).ToString("x04"));
                        break;
                }
                start = i + 1;
            }
        sb.Append(src, start, src.Length - start);
        return sb.ToString();
    }
}
Stefan Steiger
  • 68,404
  • 63
  • 337
  • 408
0

using the \uXXXX syntax can solve this problem, google UTF-16 with the name of the sign, you can find out XXXX, for example:utf-16 double quote

David
  • 1,466
  • 16
  • 19
0

I think the best answer in 2017 is to use the javax.json APIs. Use javax.json.JsonBuilderFactory to create your json objects, then write the objects out using javax.json.JsonWriterFactory. Very nice builder/writer combination.

absmiths
  • 1,024
  • 1
  • 11
  • 18