在ES6中,我們可以用JSON.stringify()
方法將JSON對(duì)象轉(zhuǎn)換成字符串。
下面是一個(gè)例子:
const person = { name: 'Tom', age: 22, hobbies: ['photography', 'traveling'] }; const personString = JSON.stringify(person); console.log(personString); // 輸出: "{"name":"Tom","age":22,"hobbies":["photography","traveling"]}"
JSON.stringify()
方法接收兩個(gè)參數(shù):第一個(gè)參數(shù)為要轉(zhuǎn)換的對(duì)象,第二個(gè)參數(shù)為一個(gè)可選的轉(zhuǎn)換選項(xiàng)。
轉(zhuǎn)換選項(xiàng)包括:
replacer
:指定函數(shù)或數(shù)組,用于選擇轉(zhuǎn)換后的屬性值space
:指定用于縮進(jìn)的空格數(shù)
例如,我們可以使用replacer
函數(shù)選擇要轉(zhuǎn)換屬性的值:
const person = { name: 'Tom', age: 22, hobbies: ['photography', 'traveling'] }; const personString = JSON.stringify(person, (key, value) =>{ if (key === 'name') { return value.toUpperCase(); } return value; }); console.log(personString); // 輸出: "{"name":"TOM","age":22,"hobbies":["photography","traveling"]}"
我們還可以使用space
選項(xiàng)指定縮進(jìn)的空格數(shù):
const person = { name: 'Tom', age: 22, hobbies: ['photography', 'traveling'] }; const personString = JSON.stringify(person, null, 2); console.log(personString); // 輸出: /* "{ "name": "Tom", "age": 22, "hobbies": [ "photography", "traveling" ] }" */
以上就是ES6中將JSON對(duì)象轉(zhuǎn)換成字符串的方法。