在JS中我們可以直接定義一個對象:
復制代碼 代碼如下:
var obj={name:"藍色",age:10};
上面其實就是所謂的JSON了,我引用下別人的復雜點的例子:
復制代碼 代碼如下:
{ firstName: "Brett", lastName:"McLaughlin", email: "brett@jb51.net" }
復制代碼 代碼如下:
{ people: [
{ firstName: "Brett", lastName:"McLaughlin", email: "brett@jb51.net" },
{ firstName: "Jason", lastName:"Hunter", email: "jb51.net" },
{ firstName: "Elliotte", lastName:"Harold", emai": "elharo@jb51.net" }
]}
{ people1: [
{ firstName: "Brett", lastName:"McLaughlin", email: "brett@jb51.net" },
{ firstName: "Jason", lastName:"Hunter", email: "jb51.net" },
{ firstName: "Elliotte", lastName:"Harold", emai": "elharo@jb51.net" }
],
people2: [
{ firstName: "Brett", lastName:"McLaughlin", email: "brett@jb51.net" },
{ firstName: "Jason", lastName:"Hunter", email: "jb51.net" },
{ firstName: "Elliotte", lastName:"Harold", emai": "elharo@jb51.net" }
],
people3: [
{ firstName: "Brett", lastName:"McLaughlin", email: "brett@jb51.net" },
{ firstName: "Jason", lastName:"Hunter", email: "jb51.net" },
{ firstName: "Elliotte", lastName:"Harold", emai": "elharo@jb51.net" }
]
}
2.後台傳輸進來的滿足JSON條件的文本格式化。
因為JSON最大的用途是AJAX應用,因此關鍵是怎樣把文本轉換成javascript對象,假設我們請求回的文本為data,那麼我們如下解析:
復制代碼 代碼如下:
data=data.replace(/\n | \r/g,"");
var obj=eval('('+data+')');
因為我們後台輸出的時候會把空格和回車符也輸出,因此這裡要用正則替換掉,然後用eval轉換成對象就可以調用了。