如何将包含等号的字符串解析为对象



我有一个字符串变量

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中显示键是正确分配的,没有引号。

最新更新