JavaScript - JSON.getJSON & JSON.parseJSON

摘要:JavaScript - JSON.getJSON & JSON.parseJSON

這是我學習 https://www.udacity.com/course/cs255 的時候看來的。

如果用原生的javascript,要怎麼parse json,及得到json string

 

JSON to String 使用

var s = JSON.stringify(JSONExample);

String to JSON 使用

var data = JSON.parse(weaponJSON);

 

參考範例,從學習網站複製程式碼及另外做測試的如下

JSONExample = {
    "frames": {
        "chaingun.png": {
            "frame": {
                "x": 1766,
                "y": 202,
                "w": 42,
                "h": 34
            },
            "rotated": false,
            "trimmed": true,
            "spriteSourceSize": {
                "x": 38,
                "y": 32,
                "w": 42,
                "h": 34
            },
            "sourceSize": {
                "w": 128,
                "h": 128
            }
        },
        "chaingun_impact.png": {
            "frame": {
                "x":1162,
                "y":322,
                "w":38,
                "h":34},
            "rotated": false,
            "trimmed": true,
            "spriteSourceSize": {
                "x":110,
                "y":111,
                "w":38,
                "h":34},
            "sourceSize": {
                "w":256,
                "h":256}
        },
        "chaingun_impact_0000.png": {
            "frame": {
                "x": 494,
                "y": 260,
                "w": 22,
                "h": 22
            },
            "rotated": false,
            "trimmed": true,
            "spriteSourceSize": {
                "x": 113,
                "y": 108,
                "w": 22,
                "h": 22
            },
            "sourceSize": {
                "w": 256,
                "h": 256
            }
        }
    }
};


parseJSON = function (weaponJSON) {
    var data = JSON.parse(weaponJSON);
    var x = data.frames["chaingun_impact.png"].spriteSourceSize.x;
    return x;
};


var s = JSON.stringify(JSONExample);
var x = parseJSON(s);

 

若是PHP則是

json_encode($JSONExample);

json_decode($s);