Firebase database WEB get data in JSON - javascript

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()))
})

Related

load JSON with JQuery

Is it possible to load JSON file once, and in further call will use loaded JSON (for ex. from cache)?
The easiest way to achieve this is to use the localStorage of JavaScript.
Let's assume you have an object named object.
You can store it this way:
// parse Object to JSON, then store it.
let jsonObject = JSON.stringify(object);
localStorage.setItem('myObject', jsonObject);
And if you want to use it again, do it this way:
// load it from storage and parse the JSON to Object.
let jsonObject = localStorage.getItem('myObject');
let object = null;
if(jsonObject){
object = JSON.parse(jsonObject);
}
Then change it according to your needs and store it again.
You can delete it by
localStorage.removeItem('myObject');
There are so many ways,
You can store your JSON file in assets folder and read them like this - https://stackoverflow.com/a/19945484/713778
You can store it in res/raw folder and read the same as show here - https://stackoverflow.com/a/6349913/713778
For basic JSON parsing, Android's in-built JSONObject should work - https://developer.android.com/reference/org/json/JSONObject.html
For more advanced JSON parsing (json-java mapping), you can look at GSON library - https://code.google.com/p/google-gson/

API Connect - 500 error when including basic Javascript

I'm trying some basic API Connect tutorials on IBM's platform (running locally using loopback) and have got completely stuck at an early point.
I've built a basic API service with some in-memory data and setter / getter functions. I've then built a separate API which takes two GET parameters and uses one of my getter functions to perform a search based on two criteria. When I run it, I successfully get a response with the following JSON object:
[{"itemId":1,"charge":9,"itemSize":2,"id":2}]
I've then tried to add a piece of server logic that modifies the response data - at this point, I'm just trying to add an extra field. I've added a Javascript component in the Assemble view and included the following code (taken from a tutorial), which I thought should modify the message body returned by the API while still passing it through:
//APIC: get the payload
var json = apim.getvariable('message.body');
//console.error("json %s", JSON.stringify(json));
//same: code to inject new attribute
json.platform = 'Powered by IBM API Connect';
//APIC: set the payload
//message.body = json;
apim.setvariable('message.body', json);
Instead of getting an extra JSON parameter ("platform"), all I get is a 500 error when I call the service. I'm guessing that I'm doing something fundamentally wrong, but all the docs suggest these are the right variable names to use.
You can't access json.platform but at that point json variable is json type. Are you sure that you can add a property to a json type variable if your json object lacks of that property? I mean: What if you first parse the json variable of json type to a normal object, then add new property, and finally stringify to json type again for body assigning purposes?
var json = JSON.parse(apim.getvariable('message.body')); //convert to normal object
json.platform = 'Powered by IBM API Connect'; //add new property
apim.setvariable('message.body', JSON.stringify(json)); //convert to json again before setting as body value
You need to get the context in some determined format, and in this function do your logic. For example if your message is in json you need to do:
apim.readInputAsJSON(function (error, json) {
if (error)
{
// handle error
apim.error('MyError', 500, 'Internal Error', 'Some error message');
}
else
{
//APIC: get the payload
var json = apim.getvariable('message.body');
//console.error("json %s", JSON.stringify(json));
if(json){
//same: code to inject new attribute
json.platform = 'Powered by IBM API Connect';
//APIC: set the payload
//message.body = json;
apim.setvariable('message.body', json);
}
}
});
Reference:
IBM Reference
You have the message.body empty, put a invoke/proxy policy before your gateway/javascript policy for example.

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!
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

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.

Write mongodb mapReduce result to a file

I have a collection in MongoDb where data in the collection has the following structure :
{userid = 1 (the id of the user), key1 = value1 , key2 = value2, .... }
I want to write mongodb mapreduce functions where i could put the userid in the map function and in the reduce function i need to write they ( key,value ) pairs in a csv (?) file such that they would be :
key1,key2, key3,...
value1,value2,value3,..
value1,value2,value3,..
value1,value2,value3,..
How can i do that with mongodb
Thanks
There is no "file output" option.
The MongoDB documentation has details on exporting data.
In particular, mongoexport allows for export by JSON or CSV which should be legible from other software.
If you want to significantly modify the data output, then you'll have to use a client library and cursor through the data while writing to a file.
You can not write data to a file directly. You have to implement such a functionality on the application level by reading the data from the collection and writing it to the filesystem in whatever format.

Categories

Resources