[英]How to parse a string containing equal signs to object
I have a string variable我有一个字符串变量
let stringValue = "{DATA={VERSION=1.1, STATE=true, STATUS=ONLINE}}"
I would like to parse it to object as result
where result
will be:我想将其解析为对象,
result
result
是:
let result = {"DATA":{"VERSION":1.1, "STATE": true, "STATUS": "ONLINE"}}
How would you convert a stringValue
to result
object so it would be possible to access the nested keys?如何将
stringValue
转换为result
对象,以便可以访问嵌套键?
console.log(result.DATA.STATUS)
Under the assumption that keys and string values are fully capitalized:在键和字符串值完全大写的假设下:
I used the regex /[AZ]+/g
and .match(regex)
to get an array of every all caps word in the string.我使用正则表达式
/[AZ]+/g
和.match(regex)
来获取字符串中每个大写单词的数组。
Create a Set
out of the the array to remove duplicates and avoid repeating the next step on the same string multiple times.从数组中创建一个
Set
以删除重复项并避免多次对同一字符串重复下一步。
Then iterate over each word and replace it in the main string with itself between quotes.然后遍历每个单词并将其在主字符串中替换为引号之间的自身。
DATA
=> "DATA"
DATA
=> "DATA"
Then replace =
with :
然后将
=
替换为:
And finally JSON.prase()
and we get the object.最后
JSON.prase()
我们得到了对象。
let stringValue = "{DATA={VERSION=1.1, STATE=true, STATUS=ONLINE}}"; let regex = /[AZ]+/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))
Here it is in JSBin to show that the keys are properly assigned without the quotes.这里在 JSBin 中显示键是正确分配的,没有引号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.