JSON Object 物件

  1. JSON Object Literals 物件文字 / 物件類型(解釋)
    1. JavaScript Objects
    2. Accessing Object Values 訪問物件值
    3. Looping an Object 遍歷一個物件

JSON Object Literals 物件文字 / 物件類型(解釋)

This is a JSON string:

'{"name":"John", "age":30, "car":null}'

Inside the JSON string there is a JSON object literal:

{"name":"John", "age":30, "car":null}

JSON object literals are surrounded by curly braces {}.

JSON object literals contains key/value pairs.

Keys and values are separated by a colon.

Each key/value pair is separated by a comma.

Keys must be strings, and values must be a valid JSON data type:

  • string
  • number
  • object
  • array
  • boolean
  • null

JavaScript Objects

You can create a JavaScript object from a JSON object literal:

myObj = {"name":"John", "age":30, "car":null};

Normally, you create a JavaScript object by parsing a JSON string:

myJSON = '{"name":"John", "age":30, "car":null}';
myObj = JSON.parse(myJSON);

Accessing Object Values 訪問物件值

You can access object values by using dot (.) notation:

const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
x = myObj.name; //John
//也可以用[]
x = myObj["name"]; //John

Looping an Object 遍歷一個物件

You can loop through object properties with a for-in loop:

const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);

let text = "";
for (const x in myObj) {
  text += x + ", ";
  
console.log(text); //name, age, car,
}

In a for-in loop, use the bracket notation to access the property values:

const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);

let text = "";
for (const x in myObj) {
  text += myObj[x] + ", ";
}

console.log(text); //John, 30, null,

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以邮件至 kimfei2014@gmail.com
github