15
15

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.

jQueryでJSONデータを扱う

Last updated at Posted at 2015-02-07

概要

jQueryを用いて、JSONデータのエンコード、デコードを行います。

下準備:jQuery拡張

<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
jQuery.extend({
	stringify : function stringify(obj) {
		var t = typeof (obj);
		if (t != "object" || obj === null) {
			// simple data type
			if (t == "string") obj = '"' + obj + '"';
			return String(obj);
		} else {
			// recurse array or object
			var n, v, json = [], arr = (obj && obj.constructor == Array);
			
			for (n in obj) {
				v = obj[n];
				t = typeof(v);
				if (obj.hasOwnProperty(n)) {
					if (t == "string") v = '"' + v + '"'; else if (t == "object" && v !== null) v = jQuery.stringify(v);
					json.push((arr ? "" : '"' + n + '":') + String(v));
				}
			}
			return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
		}
	}
});

↓コードはこちらからいただきました。
https://gist.github.com/chicagoworks/754454

エンコードとデコード

//テスト用データ
var testdata = new Object();
testdata.test1 = new Array();
testdata.test1.push("あああ");
testdata.test1.push("いいい");
testdata.test1.push(99);
testdata.test2 = "This is test."
testdata.test3 = new Object();
testdata.test3["表データ"] = true;
testdata.test3["裏データ"] = false;

//JSONエンコード
var jsonstr = $.stringify(testdata);
console.log('---jsonstr---');
console.log(jsonstr);

//JSONデコード
var data = $.parseJSON(jsonstr);
console.log('---data---');
console.log(data);

↓実行結果
json_console.PNG

↓js do it にかいてみました。
http://jsdo.it/tsunet111/A33V

15
15
0

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
15
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?