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);