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

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!

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

Related

How to render json data with # character in its key using handlebars?

This is my json data
var data = {john#gmail.com: true}
In my template i am trying this way to display data but its not working
{{data.[john#gmail.com]}}
I even tried this way
{{data.['john#gmail.com']}}
and also
{{data.john#gmail.com}}
but if i had changed my json data to
var data = {john:true}
and try
{{data.[john]}}
its working and displaying the output as true
Can anyone please point me where i am making mistake ?
It is like this data["john#gmail.com"]. Here is a good Resource to read

Firebase database WEB get data in JSON

It is possible to get data from Firebase database from Javascript (WEB) directly in JSON format ?
Currently I'm using this function and I must to parse all data and convert it to JSON array
firebase.database().ref('posts/').once('value', function(snap){
snap.forEach(function(obj){
console.log(obj.val());
// Parsing obj and saving to JSON array ...
})
})
It would be nice if I can get data directly in JSON format (like in Firebase console).
What if you just JSON.stringify() it? Does that get you what you're looking for?
firebase.database().ref('posts/').once('value', function(snap){
console.log(JSON.stringify(snap.val()))
})

Accessing JSON data when response contains both JSON data and text

Initially the content from the server was JSON data.And I was able to access the data perfectly.
{ "status":"ok", "artifact":"weblayer-war", "version":"0.0.41-test-data", "buildtime":"test-data" }
Now the response from the server has been changed to json data + text data.
{ "status":"ok", "artifact":"weblayer-war", "version":"0.0.41-test-data", "buildtime":"test-data" }
Properties for service:
=======================
ServiceEndpoint: https://somedomain:1200/web/Servlet/SOAP/Services
Certificates: false
DocumentName: note.pdf
So whether changing the content-type to application-text and using split method is the only way we can solve this or Is there any better approach?
As mentioned in the comments, mixing JSON and pure text data is wrong (as it defeats the advantage of using standardized data format) and should be avoided. Maybe that is some kind of debug log that was accidentally included in the production code?
If not, you should read just the first line of response and parse it as JSON data, ignoring the rest, hoping for no more changes in response structure ;)
You really should overthink your API design.
What about adding the text part as part of your JSON?
{
... // your JSON properties here
"serviceProperties": { // properties for service
"ServiceEndpoint": "https://somedomain:1200/web/Servlet/SOAP/Services",
"Certificates": false,
"DocumentName": "note.pdf"
}
}

Parse serialized Laravel cache data with Javascript

I'm using Laravel's cache feature to store keys in Redis. The key is stored as an array which Laravel's cache automatically serializes and unserializes into something like this:
"s:18:\"[\"bob\",\"dave\"]\";"
In PHP Laravel handles the parsing, but I need to access the data from Javascript. I am using the ioredis package in node. Everything works fine except for unserializing the data.
var Redis = require('ioredis');
var rediscache = new Redis();
rediscache.get("mykey", function (err, result) {
//Attempt to parse?
result = JSON.parse(result);
}
The key is fetched correctly, but is stuck as a string. I tried JSON.parse but this throws an error, I suppose because the format is wrong.
Unexpected token s at Object.parse (native)
How can it be correctly unserialised? I ideally want to get it as a Javascript array so a value can be altered, then re-serialised and saved back to Redis.
Many thanks.
What you have is a serialized string which contains a JSON string.
You can use a library if you don't want to write it yourself: https://github.com/naholyr/js-php-unserialize
After that, you'll have a JSON string, which you can then parse.

How to separate JSON data from ArrayBuffer receiving from websocket

I tried unsuccessful to separate JSON data from an array of buffer receiving from websocket which look like this.
{"type":"string","data":{"UklGRkIjAABXRUJQVlA4IDYjAACQswCdASqrAfAAPm0wlUemI"}}
[object ArrayBuffer]
the objective is to read them separately with proper function. My old method is parse the JSON first. If fail, pass through another function.
The reason I send them in both formats is that converting JSON data to an array or array to JSON would increase file size around three fold.
The best practice is to send them separately.
However, at the terminal I read JSON data with
var json = JSON.parse(e.data);
and read the ArrayBuffer with DataView method.
The app works properly on the surface, but if you check at console.log there are too many Uncaugth Error.
It also blocks data flow at one point, causing the stream overflow not very smooth.
Thanks for any suggestions in advance.
Got it:
if ((typeof data == 'object')) {
// this would return ArrayBuffer
} else {
// this would return JSON
}

Categories

Resources