ToString changes Javascript Object to Undefined - javascript

mysqlconnection.query("SELECT userID FROM users_session WHERE userSessionID = '" + SESSION_ID_ESCAPED + "'", function SelectCb (err, rows) {
if (err) {
throw err;
}
else {
console.log(rows[0]);
}
How do I turn row[0] into a string so that the browser can view it?
The console tells me rows[0] = {userID: 2} // This is [object Object] in any sort of transfer.
I used , var TheID = rows[0].toString // TheID is now undefined when console.log'd or sent out.

try:
var TheID = rows[0]['userID'].toString();

try this..
console.log(rows[0].userID);
you will get the userID.

Related

How to name a JSON object and writing it into a .json file?

I tried to create an empty json variable like this;
var myJSON = {
measurements: {} };
and below, I tried to push data into json and write that json into chart.json file but there is an error occured:
TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received an instance of Object
connection.query('SELECT Temprature,Humidity, Time from miTemp1', function (error, results, fields) {
if (error) throw error;
let i = 0, j = 0;
console.log(typeof (results))
while (i < results.length) {
let myDate = new Date(results[i].Time * 1000);
// console.log('Temp: ' + results[i].Temprature, 'Humidty:' + results[i].Humidity, 'Time: ' + myDate.toLocaleString());
measurements[i] = results[i];
i += 510;
j++;
}
myJSON.measurements = JSON.stringify(measurements);
console.log(typeof(myJSON));
console.log(myJSON);
console.log(new Date().toLocaleString() + ' Number of measurement: ' + j);
try {
fs.writeFileSync('./chart.json', myJSON);
console.log("JSON data is saved.");
} catch (error) {
console.error(error);
}
});
If I create json variable like var myJSON = {} there is no problem. Why this is happening? Thanks for helps ^-^
EDIT:
here is my JSON's data.
{
"0": {
"Temprature": 25.88,
"Humidity": 43,
"Time": 1628164626
},
"510": {
"Temprature": 26.22,
"Humidity": 45,
"Time": 1628169522
},
SOLUTION:
All I need to do is changing myJSON.measurements = JSON.stringify(measurements); to myJSON.measurements = measurements; and stringify the entire object.
You can't just write an object to a file. You need to serialize it first with JSON.stringify():
fs.writeFileSync('./chart.json', JSON.stringify(myJSON));
You also don't need to serialize the measurements property, since you serialize the whole object. You can replace this:
myJSON.measurements = JSON.stringify(measurements);
with this:
myJSON.measurements = measurements;

Client call JSON result show as undefined

I have a set of json data which is generated in php with json_decode function, here is the results:
I then create a html document and try to call the result using jquery $.getJSON:
var apiSrc = 'http://localhost/api/ws-data';
var showData = $('#result');
$(function(){
$.getJSON(apiSrc, function(data) {
console.log(data);
var items = data.blog.map(function (item) {
return item.key + ': ' + item.value;
});
showData.empty();
if(items.length) {
var content = '<li>' + items.join('</li><li>') + '</li>';
var list = $('<ul />').html(content);
showData.append(list);
}
});
showData.text('Loading...');
});
and the results for above is:
REST - Get JSON from PHP file on the server side
undefined: undefined
undefined: undefined
undefined: undefined
undefined: undefined
..
Its shown the key and value as undefined: undefined
What's goes wrong in the script?
I think you should access the correct properties such as pid,category etc of response,
var items = data.blog.map(function (item) {
return item.pid + ': ' + item.category;
});

Data not coming in JSON format from Splunk Javascript sdk

I am querying Splunk using javascript SDK. In the searchParams, i have given the output mode as "json_rows".
var searchParams = {
exec_mode: "normal",
output_mode: "json_rows"
};
But still when i get the output, i don't get it in a JSON format. The output is coming as an array.
Any idea what is going wrong? I tried "json_cols" and only "json" also. Same result.
Thanks in advance.
Edit:2
Some more of the code
var service = new splunkjs.Service({
username:"xxx",
password:"xxxx",
scheme:"https",
host:"xxxxxx.com",
port:"5500",
version:"5.0"
});
var searchQuery = 'search index=sn impact=1 OR impact=2 | eval time = round( strptime(impact_start,"%Y-%m-%d %H:%M:%S"), 0 )| where time >= ' + 14334627 + ' AND time<=' + 14568862 + '| bucket time span=1d | stats values(number) as incident_name by time';
var searchParams = {
exec_mode: "normal",
output_mode: "JSON"
};
service.oneshotSearch(
searchQuery,
searchParams,
function(err, results) {
if ( results ) {
var incidentResp = {};
incidentResp["data"] = results.rows;
incidentResp["error"] = null;
callback(null, incidentResp);
return;
}
else {
var errResp = {};
errResp["data"] = null;
errResp["error"] =err;
callback(null, errResp);
return;
}
}
);
I'm not 100% sure what you're asking, but let me try to help.
output_mode just tells the REST API how to serialize and return the results, usually either JSON, XML, or CSV
Given you're using the JavaScript SDK to pull data into your application and not actually having the results written to file, I would leave this as is (JSON default)
You'll find the actual data in the 'results' of the response.
eg.
service.oneshotSearch( query, params,
function(err, response) {
if (err) throw new Error ( err );
console.log( response.results );
});
Try changing this line:
incidentResp["data"] = results.rows;:
To this:
incidentResp["data"] = results.results;
... but yes, this will be an array of results.
Hope this helps

Remove characters from variable with Javascript

My variable looks as following:
response = "{ tradeofferid: '63341523' }"
I would like to remove all characters except for the letters and the semicolon.
I tried using the replace function but I get some errors.
function(err, response) {
if (err) {
throw err;
}
var result = response;
result = result.replace(/[{}]/g, "");
console.log(offerStatus);
res.end(result);
});
My console points at replace and the error log says: undefined is not a function
What I want to end up with is
response = "tradeofferid: 63341523"
response = { tradeofferid: '63341523' };
alert(response.tradeofferid);
for(var name in response) {
alert(name);
var value = response[name];
alert(value);
}
responseString = name + " : " + value;
alert(responseString);
You may try this but this answer is only specific to your question. This will not work if you have more than one attributes in "response" object.
response = "tradeofferid: " + JSON.parse(response)[tradeofferid]
... if you really want a string for display or something, but I'm guessing you actually just want to parse the JSON and pass the object around but haven't realized it yet.
You need to set something to be replaced in the .replace method. Try with:
var result = response.replace(/[^A-Za-z0-9\: ]/g, "")

Try to create HTML5 table in WebOS but failed

I try to create HTML5 table in WebOS using following JavaScript, but the table is not created.
However i can't see any further detail in the log other than the first Mojo.log "Try to create database".
2011-01-25T15:48:50.251507Z [43854] qemux86 user.notice LunaSysMgr: {LunaSysMgrJS}: com.palm.phonegap: Info: Try to create database, palmInitFramework347:2527
Do you have any idea?
Thanks..
var db;
function openDb(){
var shortName = 'mcrm';
var version = '1.0';
var displayName = 'mCRM'
var maxSize = 65536;
db = openDatabase(shortName, version, displayName, maxSize);
try {
db.transaction(
function(transaction) {
Mojo.Log.info("Try to create database");
transaction.executeSql(
'CREATE TABLE IF NOT EXISTS bookmarks'
+ ' (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, '
+ ' resource_id INTEGER NOT NULL '
+ ' resource_type TEXT NOT NULL '
+ ' url TEXT NOT NULL );',
function() {
Mojo.Log.info("DATABASE CREATED");
},
errorHandler
);
}
);
Mojo.Log.info("Is it no error?");
}
function errorHandler(transaction, error) {
Mojo.Log.info("ooopss. Error was ", error.message , " ;Error code:", error.code);
return true;
}
the cause of log file is not giving err message i.e. missing one argument of executeSql
the cause of the error i.e. missing comma at CREATE TABLE statement

Categories

Resources