[英]How to parse a string containing equal signs to object
我有一個字符串變量
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)
在鍵和字符串值完全大寫的假設下:
我使用正則表達式/[AZ]+/g
和.match(regex)
來獲取字符串中每個大寫單詞的數組。
從數組中創建一個Set
以刪除重復項並避免多次對同一字符串重復下一步。
然后遍歷每個單詞並將其在主字符串中替換為引號之間的自身。 DATA
=> "DATA"
然后將=
替換為:
最后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))
這里在 JSBin 中顯示鍵是正確分配的,沒有引號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.