我有一个字符串变量
let stringValue = "{DATA={VERSION=1.1, STATE=true, STATUS=ONLINE}}"
我想将其解析为对象result
,其中result
将为:
let result = {"DATA":{"VERSION":1.1, "STATE": true, "STATUS": "ONLINE"}}
如何将stringValue
转换为result
对象,以便可以访问嵌套的键?
console.log(result.DATA.STATUS)
假设键和字符串值全部大写:
-
我使用正则表达式
/[A-Z]+/g
和.match(regex)
来获得字符串中所有大写单词的数组。 -
从数组中创建一个
Set
,以删除重复项,并避免在同一字符串上多次重复下一步。 -
然后遍历每个单词,并将主字符串中的单词替换为引号之间的单词本身。
DATA
=比;"DATA"
-
将
=
替换为:
-
最后是
JSON.parse()
,我们得到了对象。
let stringValue = "{DATA={VERSION=1.1, STATE=true, STATUS=ONLINE}}";
let regex = /[A-Z]+/g
let objectStrings = stringValue.match(regex)
let uniqueStrings = [... new Set(objectStrings)]
uniqueStrings.forEach((string) => stringValue = stringValue.replaceAll(string, '"'+string+'"'));
stringValue = stringValue.replaceAll('=', ':');
console.log(JSON.parse(stringValue))
在JSBin中显示键是正确分配的,没有引号。