Home > OS >  Convery string to typescript object type
Convery string to typescript object type

Time:08-11

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?

CodePudding user response:

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

CodePudding user response:

Finnaly I found the way:

var obj = `{
      xAxis: {
        type: 'category',
        data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: [150, 230, 224, 218, 135, 147, 260],
          type: 'line'
        }
      ]
    }`;
    obj = obj.replace(/'/g, '"');

    var jsonStr = obj.replace(/(\w :)|(\w  :)/g, function (matchedStr) {
      return '"'   matchedStr.substring(0, matchedStr.length - 1)   '":';
    });

    obj = JSON.parse(jsonStr); //converts to a regular object
    // After you have JSON you can cast it to your own object type
    console.log(obj); 
  • Related