一、JS獲取JSON的Value值
JSON(JavaScript Object Notation)是一種輕量級的數據交換格式,而在開發中常常需要用到解析JSON數據並獲取其中的值,那麼如何獲取JSON的value值呢?
首先,通過JSON.parse()方法可以將JSON字符串轉換為JSON格式的對象,再通過”.”或”[]”訪問對象中的屬性值,從而獲取JSON的value值。
const jsonString = '{"name": "John", "age": 30, "city": "New York"}';
const jsonObject = JSON.parse(jsonString);
const name = jsonObject.name; // "John"
const age = jsonObject.age; // 30
二、JS獲取JSON的Key和Value
除了獲取JSON的value值,有時也需要同時獲取JSON的key和value值。
遍歷JSON對象可以實現獲取JSON的所有key和value值,在for…in循環中,key表示對象的屬性名,而value表示屬性值。
const jsonObject = {"name": "John", "age": 30, "city": "New York"};
for (let key in jsonObject) {
console.log(key + ": " + jsonObject[key]);
}
// "name: John"
// "age: 30"
// "city: New York"
三、JS獲取JSON的Value的長度
有時需要獲取JSON的value值的長度,可以通過字符串的length屬性獲取值的長度。
const jsonString = '{"name": "John", "age": 30, "city": "New York"}';
const jsonObject = JSON.parse(jsonString);
const nameLength = jsonObject.name.length; // 4
四、JS獲取JSON的長度
獲取JSON對象的長度(鍵值對的數量)可以通過Object.keys()方法獲取對象的所有鍵(key),再通過數組的length屬性獲取數組的長度。
const jsonObject = {"name": "John", "age": 30, "city": "New York"};
const length = Object.keys(jsonObject).length; // 3
五、JS獲取JSON的Key
同樣,遍歷JSON對象可以獲取JSON的所有key,和獲取key和value類似,在for…in循環中,key表示對象的屬性名。
const jsonObject = {"name": "John", "age": 30, "city": "New York"};
for (let key in jsonObject) {
console.log(key);
}
// "name"
// "age"
// "city"
六、JS獲取JSON的值
獲取JSON中的某個值可以通過”.”或”[]”訪問對象中的屬性值,如果想要獲取數組中的值可以通過索引值。
const jsonObject = {"name": "John", "age": 30, "city": "New York"};
const name = jsonObject.name; // "John"
const age = jsonObject["age"]; // 30
const array = [1, 2, 3];
const firstNumber = array[0]; // 1
七、JS獲取JSON的內容
獲取JSON對象的所有內容可以通過JSON.stringify()方法將JSON對象轉換為JSON字符串,也可以使用console.dir()方法在控制台中查看JSON對象。
const jsonObject = {"name": "John", "age": 30, "city": "New York"};
const jsonString = JSON.stringify(jsonObject);
console.dir(jsonObject);
八、JS獲取JSON的某個內容
如果JSON對象嵌套較深,需要獲取某個子屬性的值,可以使用”.”或”[]”深度訪問。
const jsonObject = {"name": {"first": "John", "last": "Doe"}, "age": 30, "city": "New York"};
const firstName = jsonObject.name.first; // "John"
const lastName = jsonObject["name"]["last"]; // "Doe"
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/249661.html