JSON.parse()與JSON.stringify是將JSON對象與字符串互相轉換的方法,它們還有一些參數能夠讓咱們在實際應用中更加方便,如今介紹一下它們的高級用法css
JSON.parse()json
JSON.parse(jsonString, (key, value) => {}) 能夠接受兩個參數,第一個就是咱們已經熟悉的json字符串,第二個是一個回調函數,咱們能夠對返回的每個value作處理,而後返回對應的value數組
const testJSON = { name: 'test', value: 7, }; const jsonStr = JSON.stringify(testJSON); JSON.parse(jsonStr, (key, value) => { if (typeof value === 'string') { return value.toUpperCase(); } return value; }); // {
name: 'TEST', value: 7, }
JSON.stringify()函數
JSON.stringify(jsonObject, replace, space) 能夠接受三個參數,第一個是json對象,第二個在轉成字符串前處理屬性值,第三個在字符串中插入空白符加強可讀性spa
replace: 傳入的參數能夠是一個數組,也能夠是一個回調函數,做用都是用於處理屬性值;當是一個數組時,只有在數組中存在的屬性,纔會出如今最終轉成的字符串中;當是一個回調函數時,能夠處理每個屬性值,而後返回通過處理的值,若返回值是undefined ,則該屬性值會被忽略,將不會出如今最終的字符串中。prototype
(注意: 當relace爲數組,過濾屬性時,嵌套屬性一樣會被過濾掉) code
const testJSON = { name: 'test', cities: { shanghai: 1, }, }; JSON.stringify(testJSON, ['name']); // "{"name": 'test'}"
JSON.stringify(testJSON, ['name', 'cities']); // "{"name": 'test', "cities": {}}"
JSON.stringify(testJSON, ['name', 'cities', 'shanghai']); // "{"name": 'test', "cities": {"shanghai": 1}}"
JSON.stringify(testJSON, (key, value) => { if (key === 'cities') { return 'cities'; } return value; }); // "{"name": 'test', "cities": 'cities'}"
JSON.stringify(testJSON, (key, value) => { if (key === 'shanghai') { return 9; } return value; }); // "{"name": 'test', "cities": {"shanghai": 9}}"
space: 傳入的參數能夠是String或Number的值,若是是String值,則該字符串會做爲空白符,字符串最長可爲10個字符,若是超過了10個字符,那麼會截取前10個字符,如果undefined或null,則會被忽略,不會顯示空白符;若是是Number的值,表示會有多少個空格做爲空白符,最大數值爲10,超過10也會被當作10來處理,最小爲1,小於1則無效,不會顯示空格對象
const testJSON = { name: 'test', city: 'shanghai', }; JSON.stringify(testJSON, undefined, ' '); // "{
"name": 'test', "city": 'shanghai', }" JSON.stringify(testJSON, undefined, ' '); // "{ "name": 'test', "city": 'shanghai', }" JSON.stringify(testJSON, undefined, '\t'); // "{ "name": 'test', "city": 'shanghai', }" JSON.stringify(testJSON, undefined, '...'); // "{ ..."name": 'test', ..."city": 'shanghai', }" JSON.stringify(testJSON, undefined, 7); // "{ "name": 'test', "city": 'shanghai', // 縮進7個空格
}"
toJSON方法blog
若是一個被序列化的json對象擁有toJSON方法,那麼真正被序列化的值是toJSON方法返回的值,而不是自己的對象ci
const testJSON = { name: 'test', toJSON: () => { return { toJson: 'testJson' }, }, }; JSON.stringify(testJSON); // "{"toJson": 'testJson'}"
JSON.stringify()序列化複雜的json對象
有的json對象中包含函數,那麼序列化是會忽略掉函數,當咱們想保留函數時,能夠經過replace(回調函數)來處理
const testJSON = { name: 'test', getName: () => { return 'test'; }, }; JSON.stringify(kTextJson, (key, value) => { if (typeof value === 'function') { return Function.prototype.toString.call(value); } return value; }, '\t')); // {
"name": "test", "getName": "function getName() {\n return 'test';\n }" }