-2

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!

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Ryan
  • 25
  • 1
  • https://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object – BadHorsie Oct 04 '21 at 15:23
  • That’s not a string. @BadHorsie It’s not valid JSON. Are the (randomly paired) `“` and `”` characters really part of the string or are they all `"` in reality? Can `"` or `“` or `”` occur anywhere in the key name or value name? Can the key names contain spaces? – Sebastian Simon Oct 04 '21 at 15:23
  • @SebastianSimon Yeah, he needs to do some basic reformatting of the string, then just parse it as JSON. – BadHorsie Oct 04 '21 at 15:25
  • This looks closest to XML, so use ``Object.fromEntries(Array.from(new DOMParser().parseFromString(``, "text/xml").documentElement.attributes, ({ name, value }) => [ name, value ]))``. – Sebastian Simon Oct 04 '21 at 15:35

1 Answers1

0

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
BadHorsie
  • 14,135
  • 30
  • 117
  • 191