FlyingCat FlyingCat - 2 months ago 6
Javascript Question

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

I am using postgres

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

My original data from frontend:

{
"company":[
{"name":"test company"},
{"ceo":"John"}
]
}


I do
JSON.stringify(myData.company)
and store it to postgres.

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

and the
console.log(myRetrieveData)
become

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


I used
JSON.parse(myRetrieveData)
and got '
unpexted token ,
' error.

I understand
row_to_json
turn it into json and can't be used on
JSON.parse
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

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