I have a string that I want to transform into a object, the string looks like this:
const str = `::app{port=”8080” display=”internal” name=”some name” route=”/“}`
I want to transform that string into an object that looks like this:
const obj = {
port: "8080",
display: "internal",
name: "some name",
route: "/"
}
So the string is formated in this was ::name{parameters...} and can have any parameters, not only port, name, ... How can I format any string that looks like that and transform it into a dictionary?
I tried making a regular expression to format the string, but I was not able to, the issue also is that the value could end with ” or with “, which really breaks the code I find.
Any help would be greatly appreciated!
Not sure what the rest of your data set is like, but this should work for the example given. I didn't test for edge cases like values containing escaped JSON-reserved characters or something:
const str = '::app{port=”8080” display=”internal” name=”some name” route=”/“}';
const objStr = str.match(/{[^}]*}/)[0]
.replace(/(?<={)|”|“/g, '"')
.replace(/="/g, '":"')
.split('" ').join('","');
const dic = JSON.parse(objStr);
console.log(dic.port); // 8080