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?

3
  • Have you checked when you pass that 'data' , before that you're getting it? I suggest console it and then pass. Commented Feb 8, 2018 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? Commented Feb 8, 2018 at 12:10
  • Possible duplicate of javascript string to object Commented Feb 8, 2018 at 21:13

2 Answers 2

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"]}'
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.