hitode909の日記

以前はプログラミング日記でしたが、今は子育て日記です

JSON.stringifyでオブジェクトをいい感じに整形できるぞ

JSON.stringifyでオブジェクトをいい感じに整形できます.
あまり知られていない気がしたので,皆様にお知らせしようと思います.


まずこれを読んでください.

         JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.

            replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.

            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as '\t' or ' '),
                        it contains the characters used to indent at each level.

https://github.com/douglascrockford/JSON-js/blob/master/json2.js


次に,こんなのを用意してみます.第三引数にインデントを指定しています.

var obj = {"uri":"http://kindai.ndl.go.jp/info:ndljp/pid/890720","title":"後の荒浪五郎","author":"松月堂,楳林;丸山,平次郎","x":879.9878571428574,"y":162.4457142857143,"width":2828.1225000000004,"height":2455.4464285714303,"version":1.7};
print(JSON.stringify(obj, null, "    "));


実行すると,たしかに,いい感じに整形されました.

% v8 j.js
{
    "uri": "http://kindai.ndl.go.jp/info:ndljp/pid/890720",
    "title": "後の荒浪五郎",
    "author": "松月堂,楳林;丸山,平次郎",
    "x": 879.9878571428574,
    "y": 162.4457142857143,
    "width": 2828.1225000000004,
    "height": 2455.4464285714303,
    "version": 1.7
}


Webを支える技術 -HTTP、URI、HTML、そしてREST (WEB+DB PRESS plus)