首先要了解 JSON 的概念:

<aside> 📝 JSON 是轻量级的资料交换语言,该语言以易于让人阅读的文字为基础,用来传输由属性值或者序列性的值组成的资料物件。尽管 JSON 是 JavaScript 的一个子集,但 JSON 是独立于语言的文字格式,并且采用了类似于 C 语言家族的一些习惯。

</aside>

JSON 的格式类似于 JavaScript 的对象(Object),一般格式为:

{"attr":"string", "attr_num":1, "boolean":true}

JSON 数组:

[
  {
    "attr": "string", 
    "attr_num": 1, 
    "boolean": true
  },
  {
    "attr": "string", 
    "attr_num": 1, 
    "boolean": true
  }
]
{
	"people": [
		{
			"firstName": "Brett",
			"lastName": "McLaughlin",
			"email": "[email protected]"
		},
		{
			"firstName": "Jason",
			"lastName": "Hunter",
			"email": "[email protected]"
		},
		{
			"firstName": "Elliotte",
			"lastName": "Harold",
			"email": "[email protected]"
		}
	]
}

JSON 作为一种数据传递语言,从各个角度来看,它要比 XML 易用得多。


用原生 js 解析 JSON,下面是一种比较常见且稳定的用法,但不是唯一的:

JSON.parse(data)

这个 data 内写的应该是文本形式的 json 数据,这个方法返回一个 JavaScript 对象。将它写入一个变量,就可以像调用对象一样使用 json 里的数据了。

var data = '[{"attr": "string", "attr_num": 1, "boolean": true},{"attr": "string", "attr_num": 1, "boolean": true}]';
var obj = JSON.parse(data);
document.write(obj[0].attr);//echo "string"

通过 jQuery 使用 ajax,用来解析本地 / 跨域的 json 文件内容。

$.ajax({
    url: json_path,
    type: "GET",
    dataType: "json",
    success:function(data){
        //GET 成功的操作
        //data 是接收/解析到的 js 对象
    },
    error:function(){
        //GET 失败的操作
    }
});