0

I've a table in a SQL DB in which I store a JavaScript object like this:

{content: ['First paragraph','second paragraph']}

I get it from DB and try to pass to a function which needs an object formatted like it:

this._schedaService.getObjectFromDBToPrintPdf().subscribe(data => {
    pdfMake.createPdf(data).download('tempPdf.pdf');
});

The problem is that data is always a string. I've tried JSON.parse(data) but (obviously) doesn't work.

If I write

cont temp = {content: ['First paragraph','second paragraph']};

it works.

Does anyone have a good idea?

Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
teoooo78
  • 19
  • 5
  • Have you checked when you pass that 'data' , before that you're getting it? I suggest console it and then pass. – Krina Soni Feb 08 '18 at 12:09
  • what if you `console.log` the string? What does it print? Perhaps you will need to apply a regex replace to wrap keys into double quotes, and replace single quotes with doubles? – ffflabs Feb 08 '18 at 12:10
  • Possible duplicate of [javascript string to object](https://stackoverflow.com/questions/13718326/javascript-string-to-object) – Alessio Cantarella Feb 08 '18 at 21:13

2 Answers2

1

If you use the JSON.parse JavaScript function, e.g.

var data = JSON.parse("{content: ['First paragraph','second paragraph']}");

you will receive the following error:

Uncaught SyntaxError: Unexpected token c in JSON at position 1

because your input string does not have a valid JSON object syntax.

Your input string should have this format:

'{"content": ["First paragraph","second paragraph"]}'
Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
1

I solved it in a tricky way: since JSON.parse is a specific type of the eval function, I just focused on JSON. The only solution (that I've found 'till now) is:

var str = "{content: ['First paragraph','second paragraph']}";
var obj = eval("(" + str + ")");

N.B. typeof(obj) returns

object

Here is an useful link.

Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
teoooo78
  • 19
  • 5