convert select request result to an array in nodejs using mysql - mysql

i am executing this select request in mysql data base and nodejs, the expected results are only an array with string content containing the link : ['http://hgj','http://jfhd'], but with the code that i will insert it shows me : [{link:''http://hgj},{link:''http://jfhd}] how can i remove the objects {link} and insert in the table only the string 'http...'?
query = "select link from weblist";
var res= await con.query(query, (error, response) => {
console.log('link from database', error || response);
var table = JSON.parse(JSON.stringify(response));
return table ;
});

There are a few simple steps involved in this solution:
Stringify the object using JSON.stringify. This is now a string
The string contains chars you don't want so you use string.replace() and pass a regex literal that irrespective of char position or casing, it removes the unwanted char with "" (i.e.nothing);
return that new string with a representation of your urls inside an array
One-liner solution:
let oneliner = links.map((elem) => {
return JSON.stringify(elem).replace(/[{}"'link:]/gi, "");
})
console.log(oneliner);
// [ 'http: //hgj', 'http://jfhd' ]

Related

How to extract JSON value in strangely formatted array?

I'm using a custom script for importing JSON into Google Sheets through a function. I can import values from propertys without any problem, but I have some problem with a specific array. It is a property which contains more information, but it seems the formatting makes the array into one single value instead of several (something with the slashes?). First, the script:
function getStat(url, propertyName)
{
let content = UrlFetchApp.fetch(url).getContentText();
let parsed = JSON.parse(content);
let processed = parsed.data
.filter(e =>
// Conditions go here:
e.season_format === 'Domestic League' &&
e.season === '2020/2021'
)
.map(e => e.stats[propertyName]);
return processed;
}
I want to get the value after "3" in the array called additional_info (simplified version below). But when I try to get the value, instead I get the third character in the array. I don't get "55" which is the value. I've tried with a bunch of variants. But I can't get it to work. For example, additional_info["3"] returns the third character in the array, not the value. Any tips? I've no problem getting the values of suspended_matches and home_AttackAdvantage.
{
"success": true,
"data": [
{
"season": "2020/2021",
"season_format": "Domestic League",
"stats": {
"suspended_matches": 20,
"homeAttackAdvantage": 3,
"additional_info": "{\"1\":1,\"2\":2,\"3\":55,\"4\"}"
}
}
]
}
The issue was that additional_info is yet another JSON string, so you have to parse it again.
function getStat(url, propertyName, additionalProp)
{
let content = UrlFetchApp.fetch(url).getContentText();
let parsed = JSON.parse(content);
let processed = parsed.data
.filter(e =>
// Conditions go here:
e.season_format === 'Domestic League' &&
e.season === '2020/2021'
)
.map(e => additionalProp
? [
e.stats[propertyName],
JSON.parse(e.stats.additional_info)[additionalProp]
]
: e.stats[propertyName]
);
return processed;
}
This gives you a function you can use in a formula:
=getStat(
"https://api.footystats.org/team?key=example&team_id=93",
"suspended_matches",
"330"
)
If you don't specify the third argument, it will just return a single column.

remove a field from mongodb query result in golang

This is my function from mongodb-go-driver:
func MongodbFindOne(key, value string) bson.M {
var result bson.M
opts := options.FindOne().SetShowRecordID(false)
_ = Collection.FindOne(context.TODO(), bson.M{key: value}, opts).Decode(&result)
return result
}
The function works very good but i get _id field in the result. I know the mongodb query to exclude a field from query result, But i don't know how to use it with FindOne() function:
From tutorialspoint:
db.removeIdDemo.find({},{_id:0});
From mongodb query result without field name
db.collection.find({},{_id:0, t_number:1}).toArray().map(function(ele) {return ele.t_number} );
From remove _id from mongo result (nodejs):
app.get('/itesms', function(req, res) { items.find({}, { _id: 0 }).toArray(function (err, array) {
res.send(array); }) });
To exclude fields from the result, use a projection. Use FindOneOptions.SetProjection() to set the projection.
To specifically exclude the _id field:
err = c.FindOne(ctx,
bson.M{key: value},
options.FindOne().SetProjection(bson.M{"_id": 0}),
).Decode(&result)

how insert " in numbers of my json [NODEJS]

i have a JSON like this:
{"name1":123,"name2":123,"name3":123}
i want put "" in numbers To stay like this:
{"name1":"123","name2":"123","name3":"123"}
Anybody know a nodejs code to do this?
Assuming the object is already parsed and stored in a variable somewhere, you can do:
Object.keys(myObject).reduce((o, k) => Object.assign(o, {
[k]: myObject[k].toString()
}), {})
As Judson Terrel was saying above, you should consider using JSON.stringify(myJsonObject)
but if you so desired to use regex, here it is
let str = '{"name1":123,"name2":123,"name3":123}';
let result = str.replace(/\b(\d+)/g, "\"$1\"");
console.log (result);
//console-output => {"name1":"123","name2":"123","name3":"123"}
The simplest way is to parse the JSON string to an object using JSON.parse, and then convert the object values to string with the String function, like this:
var strg = '{"name1":123,"name2":123,"name3":123}';
var obj = JSON.parse(strg);
for (var i in obj){
obj[i] = String(obj[i])
}
console.log(obj)

Storing JSON data as columns in Azure table storage

How do a format my json data and/or change my function so that it gets stored as columns in Azure table storage?
I am sending a json string to the IoT hub:
{"ts":"2017-03-31T02:14:36.426Z","timeToConnect":"78","batLevel":"83.52","vbat":"3.94"}
I run the sample function (in the Azure Function App module) to transfer the data from the IoT hub into my storage account:
'use strict';
// This function is triggered each time a message is revieved in the IoTHub.
// The message payload is persisted in an Azure Storage Table
var moment = require('moment');
module.exports = function (context, iotHubMessage) {
context.log('Message received: ' + JSON.stringify(iotHubMessage));
context.bindings.deviceData = {
"partitionKey": moment.utc().format('YYYYMMDD'),
"rowKey": moment.utc().format('hhmmss') + process.hrtime()[1] + '',
"message": JSON.stringify(iotHubMessage)
};
context.done();
};
But in my storage table, it shows up as a single string rather than getting split into columns (as seen in the storage explorer.
How do I get it into columns for ts, timeToConnect, batLevel, and vbat?
In case anyone is looking for a solution in c#:
private static async Task ProcessMessage(string message, DateTime enqueuedTime)
{
var deviceData = JsonConvert.DeserializeObject<JObject>(message);
var dynamicTableEntity = new DynamicTableEntity();
dynamicTableEntity.RowKey = enqueuedTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
foreach (KeyValuePair<string, JToken> keyValuePair in deviceData)
{
if (keyValuePair.Key.Equals("MyPartitionKey"))
{
dynamicTableEntity.PartitionKey = keyValuePair.Value.ToString();
}
else if (keyValuePair.Key.Equals("Timestamp")) // if you are using a parameter "Timestamp" it has to be stored in a column named differently because the column "Timestamp" will automatically be filled when adding a line to table storage
{
dynamicTableEntity.Properties.Add("MyTimestamp", EntityProperty.CreateEntityPropertyFromObject(keyValuePair.Value));
}
else
{
dynamicTableEntity.Properties.Add(keyValuePair.Key, EntityProperty.CreateEntityPropertyFromObject(keyValuePair.Value));
}
}
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("myStorageConnectionString");
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
CloudTable table = tableClient.GetTableReference("myTableName");
table.CreateIfNotExists();
var tableOperation = TableOperation.Insert(dynamicTableEntity);
await table.ExecuteAsync(tableOperation);
}
How do I get it into columns for ts, timeToConnect, batLevel, and
vbat?
To get these attributes as separate columns in table, you would need to defalte the object and store them separately (currently you are just converting the entire object into string and storing that string).
Please try the following code:
module.exports = function (context, iotHubMessage) {
context.log('Message received: ' + JSON.stringify(iotHubMessage));
var deviceData = {
"partitionKey": moment.utc().format('YYYYMMDD'),
"rowKey": moment.utc().format('hhmmss') + process.hrtime()[1] + '',
};
Object.keys(iotHubMessage).forEach(function(key) {
deviceData[key] = iotHubMessage[key];
});
context.bindings.deviceData = deviceData;
context.done();
};
Please note that I have not tried to execute this code so it may contain some errors.

How to read a text file and return it as a JSON object in Node JS?

I have a text file. I need to read the file inside a function and return it as a JSON object. The following is throwing an error "Unexpected token V in JSON at position 0" .
Server.js
fs.readfile('result.txt', 'utf8', function(err,data) {
if(err) throw err;
obj = JSON.parse(data);
console.log(obj);
});
result.txt looks like the following
VO1: 10 5 2
VO2: 5 3 2
I think I cannot use JSON.parse directly. How do I proceed?
Assuming the following:
Every line is separated by a newline character (\n)
Every line is separated by a : where the part in front of it is the key and the part behind it is a (space) separated string that should indicate the keys values as an array.
Below should work for your format:
fs.readfile('result.txt', 'utf8', function(err,data) {
if(err) throw err;
let obj = {};
let splitted = data.toString().split("\n");
for (let i = 0; i<splitted.length; i++) {
let splitLine = splitted[i].split(":");
obj[splitLine[0]] = splitLine[1].trim();
}
console.log(obj);
});
It could be issue with UTF-8 string format, Tried below code and it works
const resultBuffer = fs.readFileSync('result.txt');
const resultData = JSON.parse(resultBuffer.toString().trim());
Thanks to Baao for providing that answer.
As another flavor of solution, if you don't have any ":" for perhaps a list of files you could always code in a key like so:
var data = fs.readFileSync(pathAndFilename);
var testData = {};
var splitList = data.toString().split('\r\n');
for (var i = 0; i < splitList.length; i++) {
testData['fileNumber' + i.toString()] = splitList[i];
}
You need to parse the text file by yourself. You can use RegExp or some other means to extract the values, create an object out of that and then JSON.stringify it.
improving upon #baao answer:
const fs = require("fs")
fs.readFile('.czrc', 'utf8', function (err, data) {
if (err) {
console.error(err)
throw "unable to read .czrc file.";
}
const obj = JSON.parse(data)
});
Your result.txt is not valid json.
Valid json would look like this.
{
"VO1": [10, 5, 2],
"VO2": [5, 3, 2]
}