How to parse a JSON.stringify in a Firebase set? - javascript

I have the step#1 that attends others goals. However, its results doesn't work in step#2 when the variable is record in a specific node.
The code does this:
Step #1 function record(){}
localStorage.setItem(prod_id, JSON.stringify(object));
Step #2 function save(){}
var dbHistory = localStorage.getItem(prod_id, JSON.stringify(object));
const App = firebase.database();
App.ref('/wc2017/' + prod_id + '/stats').set({dbHistory});
Console
Everything is okay When I check through Console.log(dbHistory)
Result
stats = "{\"version\":\"1.2.3\",\"first_in\":0,\"batch\":{\"date\":1505374041027},\"route\":{},\"kanban\":[],\"sigma\":\"0-0\"}"
Expected Result
The json file from https://xxx.firebaseio.com/wc2017/prod_id/stats like this. How to do this?
{
"version": "1.2.3",
"first_in": 0,
"batch": {
"date": 1505368006892
},
"route": {},
"kanban": [],
"sigma": "0-0"
}

Related

Editing JSON files in NodeJS and DiscordJS

Right, so I am trying to wrap my head around editing (appending data) to a JSON file.
The file (users.json) looks like this:
{
"users": {
"id": "0123456789",
"name": "GeirAndersen"
}
}
Now I want to add users to this file, and retain the formatting, which is where I can't seem to get going. I have spent numerous hours now trying, reading, trying again... But no matter what, I can't get the result I want.
In my .js file, I get the data from the json file like this:
const fs = require('fs').promises;
let data = await fs.readFile('./test.json', 'utf-8');
let users = JSON.parse(data);
console.log(JSON.stringify(users.users, null, 2));
This console log shows the contents like it should:
{
"id": "0123456789",
"name": "GeirAndersen"
}
Just to test, I have defined a new user directly in the code, like this:
let newUser = {
"id": '852852852',
"name": 'GeirTrippleAlt'
};
console.log(JSON.stringify(newUser, null, 2));
This console log also shows the data like this:
{
"id": "852852852",
"name": "GeirTrippleAlt"
}
All nice and good this far, BUT now I want to join this last one to users.users and I just can't figure out how to do this correctly. I have tried so many version and iterations, I can't remember them all.
Last tried:
users.users += newUser;
users.users = JSON.parse(JSON.stringify(users.users, null, 2));
console.log(JSON.parse(JSON.stringify(users.users, null, 2)));
console.log(users.users);
Both those console logs the same thing:
[object Object][object Object]
What I want to achieve is: I want to end up with:
{
"users": {
"id": "0123456789",
"name": "GeirAndersen"
},
{
"id": "852852852",
"name": "GeirTrippleAlt"
}
}
When I get this far, I am going to write back to the .json file, but that part isn't an issue.
That's not really a valid data structure, as you're trying to add another object to an object without giving that value a key.
I think what you're really looking for is for 'users' to be an array of users.
{
"users": [
{
"id": "0123456789",
"name": "GeirAndersen"
},
{
"id": "852852852",
"name": "GeirTrippleAlt"
}
]
}
You can easily create an array in JS and the push() new items into your array. You JSON.stringify() that with no issue.
const myValue = {
users: []
};
const newUser = {
'id': '0123456789',
'name': "GeirAndersen'
};
myValue.users.push(newUser);
const strigified = JSON.stringify(myValue);

I am not get value which is sent in request body in specific json format

I need help in my one issue. I have write the program in that I am use map in node.js.
I am testing this program using postman by sending JSON structure, however I am not get specific value in console which I am printing.
Please see below code .
async CreateProduceMVPRateAsset(data, callback) {
// Create a new file system based wallet for managing identities.
var ProducePRICE = {};
var MVPRATE = new Map();
var MVPPRICE =[];
var MVPPRICE_BS ={};
var MVPPRICE_LB ={};
var PRODUCENAME = data.PRODUCE
console.log('PRODUCENAME', PRODUCENAME);
var COUNTRY = data.COUNTRY;
console.log('COUNTRY', COUNTRY);
var STATE = data.STATE;
console.log('STATE', STATE);
MVPRATES = data.MVPRATES;
console.log('MVPRATERATE', MVPRATES); // not getting value of MVPRATES from request body
}
JSON structure which is sending using POSTMAN
{
"username": "admin2",
"PRODUCE": "Apple",
"STATE": "MI",
"COUNTRY": "US",
"MVPRATES": {
"fuji": {
"VARIETY": "fuji",
"RATE": [
{
"UNIT": "Bussel",
"CURRENCY": "USD",
"VALUE": 10.25,
"UIDISPLAY": true
}
]
},
"gala": {
"VARIETY": "gala",
"RATE": [
{
"UNIT": "Bussel",
"CURRENCY": "USD",
"VALUE": 10.25,
"UIDISPLAY": true
}
]
}
}
}
output
Any help very appreciable
Thanks
Abhijeet
That's how logs will show up for the non-primitive type of data. Try stringifying the response like:
MVPRATES = data.MVPRATES;
console.log('MVPRATERATE', JSON.stringify(MVPRATES));
This will help you in printing actual values to the logs. A better approach will be to use a logging module like winston and configure all such things and many more.
Sorry to waste you all time I think I miss the var in front of MVPRATES. It should be
var MVPRATES = data.MVPRATES;

JSON data to Google sheet

I have a JSON link who is giving me data like -
"data": [{
"name": "123Seguro",
"domain": "123seguro.com",
"id": 1,
"slug": "123seguro"
}, {
"name": "Earn.com",
"domain": "21.co",
"id": 2,
"slug": "earn-com"
}, {
"name": "2C2P",
"domain": "2c2p.com",
"id": 3,
"slug": "2c2p"
}, {
"name": "4thWay",
"domain": "4thway.co.uk",
"id": 5,
"slug": "4thway"
}, {
"name": "51credit.com",
"domain": "51credit.com",
"id": 6,
"slug": "51-credit-card-manager"
}, ........................................
Is there is a way to take these data to Google sheet in 4 columns as it is giving 4 column data?
I tried with a script like this -
function fetch() {
var response = UrlFetchApp.fetch('mylink.json');
var res1 = response.getContentText();
var json = JSON.parse(res1);
var name = json["name"];
Logger.log(name);
}
But it is not reading the data and logger returning "UNDEFINED". can somebody help here, please.
Edit-1
On a small research, I found a script like this -
function IMPORTJSON(url,xpath){
try{
// /rates/EUR
var res = UrlFetchApp.fetch(url);
var content = res.getContentText();
var json = JSON.parse(content);
var patharray = xpath.split("/");
//Logger.log(patharray);
for(var i=0;i<patharray.length;i++){
json = json[patharray[i]];
}
//Logger.log(typeof(json));
if(typeof(json) === "undefined"){
return "Node Not Available";
} else if(typeof(json) === "object"){
var tempArr = [];
for(var obj in json){
tempArr.push([obj,json[obj]]);
}
return tempArr;
} else if(typeof(json) !== "object") {
return json;
}
}
catch(err){
return "Error getting data";
}
}
Here I am applying the formula like this - =IMPORTJSON("https://theAPILINK.json","data")
And the response is like
0
1
2
3
4
.
.
.......And at the moment I am changing from "data" to "name" it is showing "Node Not Available".
Any suggestions, please. :)
First of all it's important to understand your JSON data structure:
Data
-> 0
-> -> Name: 123Seguro
-> -> Domain: 123seguro.com
-> -> id: 1
-> -> slug: 123seguro
-> 1
-> -> Name: Earn.com
-> -> Domain: 21.co
-> -> id: 2
-> -> slug: earn-com
-> 2
....
So to reach your data, you'll always need to first open data and then select a specific "row".
function fetch() {
var response = UrlFetchApp.fetch('mylink.json');
var res1 = response.getContentText();
var json = JSON.parse(res1);
var name = json["name"];
Logger.log(name);
}
But it is not reading the data and logger returning "UNDEFINED". can somebody help here, please.
This is because you first need to open data as explained above. Then define the item of which you want to know the name. Try something like Logger.log(json["data"][0]["name"]). This should return the name of the first item in your JSON response.
Here I am applying the formula like this - =IMPORTJSON("https://theAPILINK.json","data") And the response is like 0 1 2 3 4 . . .......And at the moment I am changing from "data" to "name" it is showing "Node Not Available".
So you tell the function where to find your data and the root node (data). When you change data to name it is unable to find an element called like that. So it will return the error you've mentioned.
I would recommend to dive into your first fetch example instead of using the other function. It'll help you to understand the mechanism and process the data as you require.

Rethinkdb multiple update by one query and conditional

How can I perfom multiple updates with one query and condition, using javascript ?
For example, my docs:
[
{
"Author": "Auto",
"Number": 5,
"RandomText": "dddbd",
"Tag": "Srebro",
"id": "10fbd309-5a7a-4cd4-ac68-c71d7a336498"
},
{
"Author": "Auto",
"Number": 8,
"RandomText": "cccac",
"Tag": "Srebro",
"id": "37f9694d-cde8-46bd-8581-e85515f8262f"
},
{
"Author": "Auto",
"Number": 6,
"RandomText": "fffaf",
"Tag": "Srebro",
"id": "b7559a48-a01a-4f26-89cf-35373bdbb411"
}
]
This is my query:
UpdateIndex()
{
this.r.table(this.params.table).update((row) => {
let result;
console.log(this.r.expr([row]));
this.r.branch(
this.r.row(this.Index2).lt(10),
result = "Lucky",
result = "Good"
);
/*
if(this.r.row("Number").lt(3)) result = "Bad";
else if (this.r.row("Number").lt(5)) result = "Poor";
else if (this.r.row("Number").lt(10)) result = "Lucky";
else if (this.r.row("Number").lt(20)) result = "Good";
else if (this.r.row("Number").lt(50)) result = "Great";
else result = "Mystic";
*/
console.log(result);
return this.r.object(this.Index2, result);
}).run(this.conn, this.CheckResult.bind(this));
}
Why I want to do this ? I created second index (this.Index2 = 'Opinion'), and now I would like to populate this index with values which are describe by my condition.
But every documents are the same values (example: Bad). How can I update documents, but run condition for every document, and with one query ?
Assigning to a local variable like that (result in your case) doesn't work with the way RethinkDB's driver builds up the query object to send to the server. When you write code like above, you're storing a literal string in the local variable once on the client (rather than once per row on the server) and then sending that literal to the server in the query you return at the bottom of your function. You also can't use console.log in the way you're trying to; that runs on the client, but your query is executed on the server. You may find http://rethinkdb.com/blog/lambda-functions/ useful for understanding what the client does with the anonymous functions you pass to commands like update.
You should use do for variable binding instead:
r.table(params.table).update(function(row) {
return r.branch(r.row(Index2).lt(10), "Lucky", "Good").do(function(res) {
return r.object(Index2, res);
});
})

Update JSON with jquery error

I'm trying to update a JSON file with the value of a textarea using jquery push. I'm receiving the following error: " JavaScript runtime error: Unable to get property 'push' of undefined or null reference"
My jquery:
function submittedMsg(ctx) {
var id = $('.msg-input form').attr('id');
var newMsg = $('.msg-input textarea').val();
var url = "/ajax.aspx?vtl=ajax-conversation-json&cv=" + id;
$.getJSON(url, function (messageString, message) {
var message = [];
message.push({
msgcontent: newMsg,
sendname: sendRname,
mbrhref: mbrUrl,
datetime: ""
});
});
}
My JSON:
{
"messageString" :
[
{ "subject": "hello",
"msgstring": "5",
"unread": "1",
"datetime": "Oct 1 2013 9:59PM",
"orderid": "17",
"recipient": [
{
"mbrname": "Jane Doe",
"mbrhref": "/profile.aspx?mem=1227"
},
{
"mbrname": "John Smith",
"mbrhref": "/profile.aspx?mem=1337"
}
],
"message": [
{
"datetime":"2013-10-01T21:59:33.063",
"sendname":"Jane Doe",
"mbrhref":"/profile.aspx?mem=1227",
"msgcontent": "<p>Hi. I would like to talk with you about Dwarf Beryl Beauty</p>"
},
{
"datetime":"2013-11-26T16:29:17.037",
"sendname":"John Smith",
"mbrhref":"/profile.aspx?mem=1337",
"msgcontent": "Tough luck."
}
]
}
]
}
I don't necessarily need to use push to update the JSON file if there is a better way, I'm open to suggestions. I've verified my URL path is correct. Am I just missing something obvious? I'm new to JSON and only have passable jquery skills. Help!
Thanks in advance for any direction.
Try to use:
data.message.push
instead of:
data.messageString.message.push
Ah I see the issue, you have a local var and parameter of the same name message:
$.getJSON(url, function (messageString, message) { //here is param message
var message = []; //here is a local var parameter
message.push({ //this is probably referencing the parameter which is not an array or object that supports .push
Instead:
$.getJSON(url, function (data) { //I renamed the param to be more consistent with documentation, although it doesn't really matter, just will generate confusion
data.messageString.push({ //modify the json we were passed in the data param

Categories