12
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavascriptでJSONエスケープをする。

Posted at

JSONでよく使うエスケープの\uXXXX形式って「Unicode escape sequence」って呼ぶらしいですね。
JavaScriptで文字列をこの形式に変換する関数を作ってみました。

実行すると下記のようになります。
1行目が元の文字列、2行目がJSONエスケープした文字列、3行目がまた文字列にアンエスケープした文字列です。

hello_1234abc日本語~!@#$%^&*()_+{}[]:";<>,./?	world
hello_1234abc\u65e5\u672c\u8a9e\u007e\u0021\u0040\u0023\u0024\u0025\u005e\u0026\u002a\u0028\u0029_\u002b\u007b\u007d\u005b\u005d\u003a\u0022\u003b\u003c\u003e\u002c\u002e\u002f\u003f\u0009world
hello_1234abc日本語~!@#$%^&*()_+{}[]:";<>,./?	world
//\uXXXX形式:Unicode escape sequence

String.prototype.json_escape = function() {
	var result = '';
	var str = "" + this;
	if (str === undefined || str === null) return result;
	for (var i = 0; i < str.length; i++) {
		var ch = str[i];
		if (ch != '_' && !(ch >= '0' && '9' >= ch) && !(ch >= 'a' && 'z' >= ch) &&
			!(ch >= 'A' && 'Z' >= ch)) {
			var unicode_ch = ch.charCodeAt(0).toString(16);
			result += "\\u";
			for (var j = 0; j < 4 - unicode_ch.length; j++) {
				result += "0";
			}
			result += unicode_ch;
		} else {
			result += ch;
		}
	}
	return result;
};

//元の文字列
var str = 'hello_1234abc日本語~!@#$%^&*()_+{}[]:";<>,./?'+"\t"+'world';
//JSONエスケープ:Unicode escape sequence
var escaped_str = str.json_escape();
//元にもどした文字列
var unescaped_str = eval('{"' + escaped_str + '"}');

console.log(str);
console.log(escaped_str);
console.log(unescaped_str);

難解な文字だと処理怪しいかな...?
コメントにてツッコミよろしくお願いします。

12
12
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?