Home > OS >  How to parse a string containing equal signs to object
How to parse a string containing equal signs to object

Time:07-16

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:

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?

console.log(result.DATA.STATUS)

CodePudding user response:

Under the assumption that keys and string values are fully capitalized:

  • I used the regex /[A-Z] /g and .match(regex) to get an array of every all caps word in the string.

  • Create a Set out of the the array to remove duplicates and avoid repeating the next step on the same string multiple times.

  • Then iterate over each word and replace it in the main string with itself between quotes. DATA => "DATA"

  • Then replace = with :

  • And finally JSON.prase() and we get the object.

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))

Here it is in JSBin to show that the keys are properly assigned without the quotes.

  • Related