1

I need to store chart configuration in DB calling API. Next time I get that config as a string from DB and I need to convert it to object type. For some reason data conversion does not work, and I'm confused why. enter image description here

The result in console is this:

enter image description here

But actually, result should be like this:

enter image description here

Does someone know some trick on how to convert string to type?

Nemanja Andric
  • 625
  • 11
  • 30
  • 4
    Does this answer your question? [How to parse JSON string in Typescript](https://stackoverflow.com/questions/38688822/how-to-parse-json-string-in-typescript) – ahmet gül Aug 10 '22 at 08:09
  • No, as you can see it's not a JSON object. It's typescript object – Nemanja Andric Aug 10 '22 at 08:45
  • It is a string that's why you need to deserialize. Basically, conversion process will be string -> JSON -> casting any object type you like. – ahmet gül Aug 10 '22 at 11:05

2 Answers2

0

Your string is not valid json syntax. Make sure your string is valid. After that you can parse it to typescript object using this:

JSON.parse("your valid string source")
Ramin Quliyev
  • 382
  • 2
  • 8
0

Finnaly I found the way:

  public covertObjectToJSON(obj: string): JSON {
    obj = obj.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, '').trim(); // Strip comments
    obj = obj.replace(/'/g, '"'); // Change single quotas with double one
    var jsonStr = obj.replace(/(\w+:)|(\w+ :)/g, function (x) {
      let isNumber: boolean = !isNaN(parseInt(x));
      if (!isNumber)
        return '"' + x.substring(0, x.length - 1) + '":';
      else return x;
    });
    return JSON.parse(jsonStr);
  }
Nemanja Andric
  • 625
  • 11
  • 30