how to handle JSON response, I got this response but I don't know how to handle it. I know variable can't started with numbers, so?
let result = [{"1d":{"volume":"22275409068573.73","price_change":"56446.71564507","price_change_pct":"0.0121","volume_change":"-13864857829188.44","volume_change_pct":"-0.3836","market_cap_change":"9216448958327.75","market_cap_change_pct":"0.0121"}}];
How to parsing"1d"?
I try JSON.parse(result[0].1d); but error happened
If you don't want to use ["prop"] to get value, you can change all props that starts with a number like in the example.
Check this link
var json = JSON.stringify(result);
json = json.replace(/,"[0-9]|{"[0-9]/g, function (x) {
return x.substring(0,1)+'"num'+x.substring(2);
});
result = JSON.parse(json);
var whatIwant = result.num1d;
You can't use JSON.parse for JSON object.
If you want to get value of 1d. Try this
result[0]["1d"]
Related
I would like to create a .env file that has a single environment variable that provides multiple key/values readable by node.js.
For instance:
USERNAME=firstname:John,lastname:Doe
Then something like:
require('dotenv').config()
let myEnvVariable = process.env.USERNAME
let firstName = myEnvVariable.firstname
let lastName = myEnvVariable.lastname
console.log(fistName, lastName)
// expected result: John Doe
Is something like this possible? If so, how do I go about it?
It might be easiest if you just put JSON as the environment variable value. Then, you can just get the value of the environment variable and do JSON.parse() on it and have a fully formed Javascript object as the result. Then, you don't have to invent your own format and don't have to write your own parsing code.
In your environment:
USERNAME={"firstname":"John","lastname":"Doe"}
Then, in your code:
const user = JSON.parse(process.env.USERNAME);
console.log(user.firstname);
console.log(user.lastname);
FYI, this is exactly the kind of things JSON was invented for - a text-only standard format for expressing data that can be generated or parsed easily from nearly any language.
I've never heard of anything like that... but you could work defining your own format for the variable so that you can achieve something like that...
Following your example you could work on a parser that would do it...
const USERNAME="firstname:John,lastname:Doe,phone:countryCode:55,phone:number:99999999999";
const parse = str => {
const output = {};
str.split(',').forEach(part => {
const keys = part.split(':');
const value = keys.pop();
let def = output;
keys.forEach((key, idx) => {
if (idx === keys.length - 1) return def[key] = value;
if (!def[key]) def[key] = {};
def = def[key];
});
});
return output;
};
console.log(parse(USERNAME));
I've never heard of anything like that... but you could work parsing out the format that you created yourself...
my first steps with node...
I want to access to the response status when calling a function like this:
var unirest = require('unirest');
function doPut(){
var Request = unirest.put('some_url').type('json').send('some_json');
return Request.end(function (response) {
return response.status;
});
}
console.log("Status is: " + doPut())
Inside the inner code, the value of status is "204" but when asking outside the function doput() i get an object,how can I pass the value from the inner function?
Thanks.
The reason [object Object] is returned is because you're just printing the object. Either (if you know the output format) print a specific value or use JSON.stringify(doput()).
I am working with node-red and I would like to create my custom function to access some index from the incoming message. The incoming message looks like this
{ "node": "02010101", "base64": "Cro=" }
It comes out from the json function block in node-red (A function that parses the msg.payload to convert a JSON string to/from a javascript object. Places the result back into the payload), I can use the debug block to obtain the index base64, however if I try to do the same with my own function to proces that later, I cannot and I get the error
TypeError: Cannot assign to read only property '_msgid' of Cro=
My function is really silly for now it is just
return msg["base64"];
I understand that it complains that there is no property in the incoming message, so I would like to access to hat index, how can I do it?
EDIT: if I set the debug block to show the whole message object not just the msg.base64 itself, I get this
{ "node": "02010101", "base64": "Cro=", "_msgid": "6babd6e.f945428" }
A function node should return a whole msg object not just a string.
If you want to just send on the string value you should do something like this:
msg.payload = msg.payload["base64"];
return msg
THe solution was easy, just return the whole message and not just a field. Using the following snippet made it work.
Getting decrypted module
msg.payload = msg.decrypted;
return msg;
base64Decode
msg.payload = msg.base64;
return msg;
I've created chat application based on this project but what I want to do now is to have parser for smilies. For example, If I write something like:
What's up? :)
That can be parsed as "What's up? [image here]". Also, when someone visits room, all messages from that room needs to be parsed too. What's the easiest way to do this?
P.S. App doesn't have database.
var smileyMap={
"smile.png":[":)",":-)"],
"sad.png":[":(",":-("]
};
var insertSmiley=function(basePath,smileys){
var replacements=[];
Object.keys(smileys).forEach(function(file){
var _file="<img src=\""+basePath+file+"\"\>";
smileys[file].forEach(function(chars){
var reg=new RegExp(chars.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"),"g");
replacements.push([reg,_file]);
});
});
return function(text){
return replacements.reduce(function(line,replacement){
return line.replace(replacement[0],replacement[1]);
},text);
}
}("http://example.com/images/",smileyMap);
"http://example.com/images/" Has to be the root Path of the smiley Images.
smileyMap has to be an Object with the filename as the key, and the smileys to be replaced as an Array.
insertSmiley("Hello World :-)")
Results in:
Hello World <img src="http://example.com/images/smile.png">
You can use simple string interpolation based on Regex or whatever you want.
Let's imagine that we have map of smiles:
const SMILES_MAP = {
':)': 'http://link-to-smiley.png',
':0': 'http://link-to-another-smiley.png'
};
Also we have a string of our message called message, for instance. Let's build a function that replace all smiles with images:
function buildMessage(message) {
let smiles = Object.keys(SMILES_MAP);
smiles.forEach(smile => message = message.replace(smile, SMILES_MAP[smile]));
return message;
}
Call function with message arguments and get result:
buildMessage("Hello there :)"); // Returns "Hello there http://link-to-smiley.png"
I'm trying to get the HTML of a website using restler. But when I try to get the relevant part of result, I always get the error,
"TypeError: Cannot read property 'rawEncoded' of undefined".
'rawEncoded' sometimes is 'res'. I think it changes based on processing time.
I'm trying to get result.request.res.rawEncode from restler get result.
My function:
var rest = require('restler');
var loadHtmlUrl = function(weburl) {
var resultstr = rest.get(weburl).on('complete', function(result) {
var string = result.request.res.rawEncode;
return string;
});
return resultstr;
};
Then:
var htmlstring = loadHtmlUrl('http://google.com');
Maybe restler is the entirely wrong way to go. Maybe I don't understand it completely. But I'm definitely stuck...
Thanks!
Would your return resultstr; not run before the on('complete' callback gets called because it is asynchronous, therefore resulting in your htmlstring being null? I think you need to have a callback as a parameter to your loadHtmlUrl like so:
var rest = require('restler');
var loadHtmlUrl = function(weburl, callback) {
var resultstr = rest.get(weburl).on('complete', function(result) {
callback(result.request.res.rawEncode);
});
};
And then call it like so:
var htmlstring = null;
loadHtmlUrl('http://google.com', function(rawEncode) {
htmlstring = rawEncode;
//Do your stuff here...
});
I think that will resolve future problems you will have. However, I think the real problem you're facing is that result.request does not have the property of res. I'm thinking that my change above may fix this problem (not quite sure how). If not, then I would recommend looking at what properties result.request has as a debugging starter...