Note for Javascript JSON variable

太常搞混了,只好自己簡單筆記一下。


這是一個JSON object,

<script>
var text = {}; //a json object
</script>

JSON object,內容必須是name/value。

<script>
var text = {};
var text = {"name":"Joe"};
var text = {name:"Joe"};
</script>

上例最後兩行,name有沒有" "沒差,差在JSON.parse()。

<script>
var text = {"name":"Joe"};
var text2 = {name:"Joe"};
try{
  obj = JSON.parse(text);
  obj2 = JSON.parse(text2); //Error !
}catch(e){
  alert(e);
}
</script>

這是一個JSON array,

<script>
var text = []; //json array
</script>

JSON array,可以放N個JSON object。

<script>
var text = [];
var text = [{}, {}];
var text = [{"name":"Joe"}];
var text = [{"name":"Joe"}, {"name":"Amy"}];
</script>

最後,
JSON object的值,可以是一般常數,也可以是一個JSON array

<script>
var text = {[]}; //Error: Need key for JSON object!
var text = {"people": []};  //OK
</script>

裡頭的JSON array,一樣可以放N個JSON object。

<script>
var text = {"people": []}; 
var text = {"people": [{"name": "Joe"}]}; 
</script>

常看見JSON檔的起手式是{ },就是用一個JSON object包住所有內容。

留言

這個網誌中的熱門文章

AngularJS (1) 宣告ng-app

href with relative url 在錨點使用相對路徑