1. 判斷是否是合法的JSON字符串
/**
* 判斷是否是合法的Json字符串
* @param str - 字符串
*/
const isJsonStr = (str: string) => {
if (typeof str === 'string') {
try {
const obj = JSON.parse(str)
if (typeof obj === 'object' && obj) {
return true
} else {
return false
}
} catch (e) {
return false
}
}
return false
}
2. JSON String 數(shù)據(jù)轉(zhuǎn) MAP
通過JSON.stringify將JSON轉(zhuǎn)為String
再先執(zhí)行第一步isJsonStr ,判斷字符串是否為JSON字符串
再將JSON String 數(shù)據(jù)轉(zhuǎn) MAP文章來源:http://www.zghlxwxcb.cn/news/detail-636465.html
/**
* JSON String 數(shù)據(jù)轉(zhuǎn) MAP
* @param jsonStr - JSON String
*/
const jsonStrToMap = (jsonStr: string) => {
const jsonObj = JSON.parse(jsonStr)
const map = new Map()
for (const k of Object.keys(jsonObj)) {
map.set(k, jsonObj[k])
}
return map
}
3. MAP 數(shù)據(jù)轉(zhuǎn) JSON String
MAP 數(shù)據(jù)轉(zhuǎn) JSON String
如果只想要json數(shù)據(jù)可直接return obj 即可文章來源地址http://www.zghlxwxcb.cn/news/detail-636465.html
/**
* MAP 數(shù)據(jù)轉(zhuǎn) JSON String
* @param map - MAP對象
*/
const mapToJsonStr = (map: Map<string, any>) => {
const newMap = cloneDeep(map)
const obj: any = {}
newMap.forEach((v, k) => (obj[k] = v))
const JsonStr = JSON.stringify(obj)
return JsonStr
}
到了這里,關(guān)于js中json與map數(shù)據(jù)互相轉(zhuǎn)換的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!