Getting Array out of JavaScript Object - javascript

I try to get messages from a Server via Websocket and this works so far.
I get back an Javascript Object and want to filter out the data I need to put it into the state of my react app.
this is the code im using at the moment:
connection.onmessage = function (newMessage) {
if(newMessage.data == '{"msg":"ping"}' ){
connection.send('{"msg": "pong"}')
}
newMessage = JSON.parse(newMessage.data)
console.log(newMessage.fields)
}
and this is the object I get back:
Javascript Object
I need the Array at args/0
how do i get it?
Thank You

It's probably not a good idea to rewrite newMessage in your connection.onmessage function, and may be add more logs when you get a new message. Can you try this version ?
connection.onmessage = function (newMessage) {
console.log("Received new message :", newMessage.data);
if(newMessage.data == '{"msg":"ping"}' ){
connection.send('{"msg": "pong"}')
}
var parsedMessage = JSON.parse(newMessage.data);
if (parsedMessage.msg === "changed") {
console.log("Received changed message :", parsedMessage.fields.args);
}
}
Hope this helps!

you can access the 'args' data in the json object like 'newMessage.args'
var newMessage = {eventName: 'aname', args: ['data1','data2'] }
document.getElementById('output').innerHTML = newMessage.args
<div id='output'></div>

Related

JavaScript Invalid export data. Please provide an array of objects

Im writing a function to export data pulled from C# to a csv file in JavaScript. The data is trying to be passed into an active webpage with live data. The goal is to export said data from C# string to the clients window hence the transfer to JavaScript (if my understanding is right). Then the JavaScript function in the page will download to the users window.
My issue is why am I have the invalid export data, please provide an array of objects output when I think I provide it one?
C# Code:
protected string test()
{
MyRequest request = new MyRequest();
request.Id = "TEST";
// Cant post this class but this is what I do
var tmp = new ExistingClassOfMine();
// pulls the data from the existing class through GetResponse();
// Then convert to json string
string data = JsonConvert.SerializeObject(tmp.GetResponse(request));
// Data found from breakpoint: {"Slot1":[{"Name":"TJ", "ID":"123"},{"Name":"Joe","ID:456"}], "TotalCount":2}
return data;
}
JavaScript:
function exportToExcel() {
console.log("Exporting to Excel");
isExporting = true;
const fileName = 'NameList';
const exportType = 'csv';
var data = <%=this.test()%>;
var readData = data["Slot1"];
var myArray = [];
// Followed a stack article to create this
for (var i in readData) {
myArray.push(readData[i]);
}
// Logging stuff for debugging
console.log("Data from C#");
console.log(data);
console.log(typeof (data));
console.log("Data we want to export");
console.log(readData);
console.log("Parsed Data?");
console.log(myArray);
// fails here with the error Invalid export data, please provide an array of objects
// which I thought I did with my for loop up a few lines
window.exportFromJSON({myArray, fileName, exportType});
isExporting = false;
}
function onRequestStart(sender, args) {
if (isExporting) {
args.set_enableAjax(false);
}
}
Log output:
Look, your triying to change the name of the key which is sent to exportFromJSON. The right way to name the key is data no myArray.
Change:
myArray
to
data
or assign myArray to data key
window.exportFromJSON({data:myArray, fileName, exportType});

Why is getFields() returning an empty object?

I am working on a Google Data Studio community connector, and I am trying to display only one field to start with. All of the code is in the code.gs file, except getAuthType() and isAdminUser() is in Auth.gs.
The issue is that once getData() is called, getFields() returns an empty object. Here is the log:
It looks like getSchema() is working correctly, here is the log from that function:
Here is the getFields() function:
function getFields() {
var fields = cc.getFields();
var types = cc.FieldType;
fields
.newDimension()
.setId('device')
.setName('Device')
.setType(types.TEXT);
return fields;
}
Here is getData():
function getData(request){
console.log('getData request', request);
request.configParams = validateConfig(request.configParams);
console.log('getFields()', getFields(), typeof getFields());
var requestedFields = getFields().forIds(
request.fields.map(function(field){
return field.name;
})
);
try{
console.log('start request');
var apiResponse = fetchDataFromApi(request);
var data = formatData(apiResponse, requestedFields);
}catch (e){
cc.newUserError()
.setDebugText('Error fetching data from API. Exception details: ' + e)
.setText(
'The connector has encountered an unrecoverable error. Please Try again later.'
)
.throwException();
}
return {
schema: requestedFields.build(),
rows: data,
}
}
getSchema():
function getSchema(request){
var schema = {schema: getFields().build()};
console.log(schema);
return schema;
}
The community connector is initialized outside of all functions in the same file:
var cc = DataStudioApp.createCommunityConnector();
I looked through the documentation, but I cannot find anything that would cause getFields() to return an empty object, based off what I have. Any thoughts?
I thought that getFields() returning an empty object was causing my app to display the fields incorrectly, but the issue was that the data I was passing to the app was in the incorrect format.
getFields() isn't useful until it is called with build() (i.e. getFields().build() )
I think it is expected behavior to receive an empty object for getFields() alone.

Electron webContents.send does not always work

I use the following to send some data to another window;
try{
win.webContents.once('dom-ready', () => win.webContents.send('send-data', data));
}
catch(err){
console.log("Caught ",err);
}
And for receivig;
ipcRenderer.on('send-data', function (event,data) {
console.log("Loaded ", data);
});
The thing is, the "data" here is sometimes assembled very quickly and it works fine. However, sometimes it takes a while and the other window is already loaded at this point. No data is received in that case, and no error message either. But then I can simply use the following to send it without problems;
win.webContents.send('send-data', data)
I couldn't find a way to apply for both cases. Any suggestions?
The short answer is no.
Electron doesn't have a function to wait for the window to load, then send a message, or send a message right away if the window's already loaded.
However this can be done with some simple code:
var hasWindowLoaded = false;
var hasDataBeenSent = false;
var data = {};
win.webContents.once('dom-ready', () => {
hasWindowLoaded = true;
if (!hasDataBeenSent && data) {
win.webContents.send('send-data', data);
hasDataBeenSent = true;
}
});
// Now add this where you build the `data` variable.
function loadData () {
data = {'sampleData': 'xyz'};
if (!hasDataBeenSent && hasWindowLoaded) {
win.webContents.send('send-data', data);
hasDataBeenSent = true;
}
}
Once the data's loaded in loadData it'll check if the window's finished loading and if it has then it sends the data right away.
Otherwise it stores the data in a varible (data) and once the window loads it sends it to the window.
Another approach that you may want to consider is sending data to the browserWindow using query strings.
const data = { hello: "world" }; // sample data
// send it using query strings
browserWindow.loadFile(YOUR_HTML_FILE_PATH, {
query: { data: JSON.stringify(data) },
});
// parse this data in the browserWindow
const querystring = require("querystring");
const query = querystring.parse(global.location.search);
const data = JSON.parse(query["?data"]);
console.log(data); // { hello: "world" }

JS/NodeJS/VSCode - How to step into a console logged object [duplicate]

In the below code (running on Node JS) I am trying to print an object obtained from an external API using JSON.stringify which results in an error:
TypeError: Converting circular structure to JSON
I have looked at the questions on this topic, but none could help. Could some one please suggest:
a) How I could obtain country value from the res object ?
b) How I could print the entire object itself ?
http.get('http://ip-api.com/json', (res) => {
console.log(`Got response: ${res.statusCode}`);
console.log(res.country) // *** Results in Undefined
console.log(JSON.stringify(res)); // *** Resulting in a TypeError: Converting circular structure to JSON
res.resume();
}).on('error', (e) => {
console.log(`Got error: ${e.message}`);
});
Basic console.log will not go through long and complex object, and may decide to just print [Object] instead.
A good way to prevent that in node.js is to use util.inspect:
'use strict';
const util = require('util'),
obj = /*Long and complex object*/;
console.log(util.inspect(obj, {depth: null}));
//depth: null tell util.inspect to open everything until it get to a circular reference, the result can be quite long however.
EDIT: In a pinch (in the REPL for example), a second option is JSON.stringify. No need to require it, but it will break on circular reference instead of printing the fact there is a reference.
Print the whole object, it will not have problems with recursive refferences:
console.log(res);
Here's an example for you to see how console.log handles circular refferences:
> var q = {a:0, b:0}
> q.b = q
> console.log(q)
{ a: 0, b: [Circular] }
Also, I would advise to check what data are you actually receiving.
By using the http request client, I am able to print the JSON object as well as print the country value. Below is my updated code.
var request = require('request');
request('http://ip-api.com/json', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(response.body); // Prints the JSON object
var object = JSON.parse(body);
console.log(object['country']) // Prints the country value from the JSON object
}
});
This can print the key of the object and the value of the object in the simplest way. Just try it.
const jsonObj = {
a: 'somestring',
b: 42,
c: false
};
Array.from(Object.keys(jsonObj)).forEach(function(key){
console.log(key + ":" + jsonObj[key]);
});
In 2021, I just printed using
app.post("/",(req,res) => {
console.log("HI "+JSON.stringify(req.body));
res.send("Hi")
});
and got my output as HI {"Hi":"Hi"}.
I sent
{
"Hi": "Hi"
}
as my post request body.
Only doing console.log(req.body) printed [object Object] on console but now this works.
Use console.dir and set the depth.
console.dir(obj, { depth:10 })
Alternatively you can set the default depth to change the console.log depth.
require('util').inspect.defaultOptions.depth = 10
All of this and details about this can be found in nodejs training.
https://nodejs.dev/learn/how-to-log-an-object-in-nodejs
You do not actually get data in res. You need on('data') and on.('end')
body is a string. It gets append on data received, so on complete you will need to parse data into json
http.get("http://ip-api.com/json", function(res) {
var body = '';
res.on('data', function(data){
body = body + data;
});
res.on('end', function() {
var parsed = {};
try{
parsed = JSON.parse(body); // i have checked its working correctly
}
catch(er){
//do nothing it is already json
}
console.log(parsed.country);
});
});
Noe from parsed which is a json object, you can get any property
You can pass two arguments to console.log()
Try this code after installing "yargs" And it will print whole object
console.log('object is' , yargs.argv);
I think may be it will help you to print whole object :)

Why do I get an error when putting a JSONObject into an indexedDB database?

I am currently trying to get an indexedDB database running. However, I am struggling with some issues regarding indexedDB's put method. Although the keypath is defined and the JSONObject that is handed over contains a value which is named in the same way as the defined keypath, the put method causes the following error:
Uncaught DOMException: Failed to execute 'put' on 'IDBObjectStore': Evaluating the object store's key path did not yield a value.
In order to make sure that the JSONObject really contains the value that shall be used as the key, I am logging the object. Thats what it looks like:
{"key":102019,"month":10,"year":2019,"spendings":[{"type":{"name":"Technology","importance":70,"iconURL":"./Resources/Technology.png"},"cost":"1500","name":"Macbook pro","timestamp":1571696285911}],"budget":0}
The code that is being used to store the data is the following:
function callbackSaveSpendingMonth(database, spendingMonth) {
let userName = defaultUserName;
let transaction = database.transaction(userName, "readwrite");
let objectStore = transaction.objectStore(userName, { keyPath: 'key' });
let JSONspendingMonth = JSON.stringify(spendingMonth);
console.log(JSONspendingMonth);
let request = objectStore.put(JSONspendingMonth);
request.onsuccess = function (event) {
console.log("The month " + spendingMonth.getMonth() + "/" + spendingMonth.getYear() + " has been saved successfully!");
}
transaction.oncomplete = function (event) {
console.log("A connection to indexedDB has successfully been established!");
}
}

Categories