FlyingCat FlyingCat - 1 year ago 42
Javascript Question

How to retrieve data from DB and turn them to object in my case?

I am using postgres

function to get the data that were stored through
. However, when I retrieve it and do
, it gave me "
unexpected token ,
" error message.

My original data from frontend:

{"name":"test company"},

I do
and store it to postgres.

When I retrieve it, I have
function to get the data.

and the

{"{\"name\":\"test company\"}","{\"ceo\":\"John\"}"}

I used
and got '
unpexted token ,
' error.

I understand
turn it into json and can't be used on
but the function is needed for my other data.
I am not sure how to fix this. Can anyone help me about it?
Thanks a lot!

Answer Source

Looks like the JSON that you retrieved from the query is not of the proper format for it to be parsed. Inorder to avoid this please make sure that the JSON being stored into the DB is of proper JSON format, so that it parsed.If this is not achievable the response obtained from the db has to be modified to proper JSON. With the above data it can be done as follows.

var improperJson = '{"{\"name\":\"test company\"}","{\"ceo\":\"John\"}"}';
var properJson = improperJson.replace(/","/g, ",").replace(/^{"/, "[").replace(/"}$/, "]");
console.log(JSON.parse(properJson));//should give you the parsed JSON