How to get a value from JSONObject in NodeJS? - javascript

I have a node js app. I use JSON web token for authentication. I split my token as 3 parts (header, payload, signature) to use them for a spesific code.
My payload JSON object is as shown in the below:
payload= {"email": "minnela#gmail.com", "iat" : "23254324", "exp": "4323456"}
I need to get the value of "email". How can I get it in Node.js?

There are multiple ways of doing this.
Easiest ways: const payloadEmail=payload.email //minnela#gmail.com
Using ES6 feature : const {email} = payload //minnela#gmail.com
Using JS inbuild method that converts object to array :Object.values(payloadEmail) //["minnela#gmail.com","23254324","4323456"]
Another way is const payloadEmail=payload["email"] //minnela#gmail.com
Note: I am assuming that the naming convention in your sample payload i.e payload= {"email": "minnela#gmail.com", "iat" : "23254324", "exp": "4323456"} are exactly same as you want. Incase it has different property names then you need to change the names accordingly.

You can simply use payload.email
Or you can use object destructuring
const {email} = payload;
console.log(email); // prints minnela#gmail.com

Related

Postman scripting: how to refrence a json node with web address for a name

I'm currently working with a bearer token I need to get some data out of to continue a user journey. I found the following code that does the decoding for me
var jsonData = JSON.parse(responseBody);
const payload = jsonData.Result.AccessToken.split('.')[1]; // Assuming the JWT is in id_token
const parsed = JSON.parse(atob(payload));
It uses atob sandboxed script to decode base 64 encoded payload, when decoded the payload looks a little like this:
{
"http://mytestsite.uk/roles": [
"user"
],
"http://mytestsite.uk/id": "8d2c3de9-4fa2-a58e-68109d977",
"http://mytestsite.uk/email": "tst3#mytestsite.uk",
"sub": "500b416c8942bb0069b98a3c",
"aud": "api.tst.mytestsite.uk",
"iat": 1615544685,
"exp": 1615631085
}
Normally, I would reference the payload body item I want (e.g. sub) like so:
pm.environment.set('sub', parsed.sub);
However, I want to reference "http://mytestsite.uk/id" and am uncertain how to do it.
parsed.http://mytestsite.uk/id
The above causes the script to error and I can't encode it, as that doesn't remove the dots, I obviously can't pass it as a string - I guess I'm unclear on how to correctly pass this name to reference the JSON object correctly.
You should be able to reference it this way:
pm.environment.set('id', parsed['http://mytestsite.uk/id'])

Extract variables from json string

Context :
I'm making a Discord bot using the discord.js library and MongoDB (with mongoose). I created a script that can construct messages from data stored in my MongoDB database. For exemple, if an user on my Discord server type "!hello", it will query my database to construct a reply like "Hello to you!".
I store my reply message data in an document like this :
{
"command": "!hello",
"content": "Hello to you!"
}
(I voluntary omitted some properties here that are useless in the context of my question)
And retrieve it in my code with something like :
let retrievedReply;
await mongo().then(async mongoose => {
try {
let query = {command: message.content};
retrievedReply = await replySchema.findOne(query);
} finally {
mongoose.connection.close();
}
});
message.reply(retrievedReply.content);
My issue :
Now, imagine I want it to respond "Hello username!".
If I didn't construct my reply using data from mongo I could simply do something like :
message.reply(`Hello ${message.member.nickname}!`);
or
message.reply("Hello " + message.member.nickname + "!");
So, in other words, using backticks and ${} syntax or (but I like it less), splitting my string and concatenate my property value like the second example.
The thing is, we can't store a string inside backticks in json format (used by MongoDB). So even if I build my document like so :
{
"command": "hello",
"content": "Hello ${message.member.nickname}!"
}
${message.member.nickname} would not be interpreted like a property value but just like a simple string.
The 1000$ question :
How can I use this property inside my code? I thought about extracting it using regex but it does not change the fact that it will still be a string. Is there a way to "convert" from a string to an usable variable?
EDIT
Since Brettski asked me (rightfully), here is an example of what I want :
message.member.send(`Hello ${message.member}!`);
This message.member property here represent a member object of a Discord guild. It contains a lot of things like its permissions on the guild, its roles, etc.
When we use a member object into a message, Discord will make a mention of the member like bellow.
It works the same with other properties like channels for example. Users can then click on those to see informations about the member or to go directly to the channel, etc. I want to be able to use this.
That is correct you will not be able to store a string literal in Mongo or other way.
One though I had is to put a token in your string and then do a replace on it in message.reply() or before it.
example:
const helloCommand = {
"command": "hello",
"content": "Hello ~~membernickname~~!"
};
In this example the token to replace is ~~membernickname~~
You can use something like this to do the replace:
const command = JSON.parse(helloCommand)
message.member.send(command.content.replace('~~membernickname~~', message.member));
The resulting string being sent to the send() command is the same. So if the nickname is #brettski, the string 'Hello #brettski' will be sent to the send() command.
In your example:
message.reply(`Hello ${message.member.nickname}!`);
the part:
`Hello ${message.member.nickname}!`
is a string literal (template literals). What the function message.reply() ends up getting is 'Hello Nickname' a string. So the replace should work. As a test you can hard code the string used in message.reply() to a known nickname and it should provide the results you expect.
Ok so, #Brettski put me on the right track with the fact that I can use users' or channels' IDs directly as strings within the message and between specific tags.
To reuse the example in my question, I can use this syntax to mention an user :
"<#idOfTheUser>"
What I did is if I want to mention the author of the command in my reply, I put the text in my mongoDB document as so :
const helloCommand = {
"command": "hello",
"content": "Hello $member$!"
};
Then, in my code, I can simply use :
message.reply((retrieveReply.content).replace(/\$member\$/g, `<#${message.member.id}>`))
Of course, I wanted to use more properties so I did a function like :
const messageContentReplace = function(content) {
const replaceableStrings = {
"$member$": `<#${message.member.id}>`,
"$memberName$": message.member.displayName,
"$guild$": message.guild.name
}
return content.replace(/(\$member\$)|(\$memberName\$)|(\$guild\$)/g, match => {
return replaceableStrings[match];
});
(in reality, I did something more complexe because I use an embed message as my response with multiple fields etc... See here about embeds)

How to send an object in postman

I was trying to make a post request to the api route I just created.
In the backend I have something like this
console.log(typeof req.body)
console.log(req.body)
const { firstName, lastName, email, phoneNumber } = req.body
console.log(`Variable Values`, firstName, lastName, email, phoneNumber)
Here I am getting typeof as String and body as this
{
firstName: "Varun",
lastName: "Bindal",
email: "iva#gmail.com",
phoneNumber: "+91-8888"
}
What I want is that the typeof to be object so I can de-structure it, How can I make a request from postman in this case (I don't want use JSON.parse)
Click the "Text" beside it will show you a dropdown. Just choose "JSON" instead of "Text"
Choose the JSON option as shown in the picture.
You should change the type of body from raw text to JSON (application/json) by clicking on the text button right next to your GraphQL option.
Your object body is of type text. Change it to JSON using the little dropdown and the POST request will work.
Cheers!
Why don't you want to use JSON.parse?
It's important to know that JSON and a javascript object are two different things.
JSON is a data format format that can be used in various environments while a javascript object is a data structure/concept in javascript.
When making a HTTP request you can send data via a few different methods. A few prominent ones being XML, Binary and JSON (They all will be represented as text, even binary).
Since you're building a API with javascript I would recommended that you use JSON in your requests and responses. JSON has also somewhat become the "standard" for APIs these days. It's also very easy to parse JSON to javascript objects and the other way around.
Please note that you maybe also need to tell postman to set the Content Type Header to application/json. You also would need to change your body to be actual valid JSON:
{
"firstName": "Varun",
"lastName": "Bindal",
"email": "iva#gmail.com",
"phoneNumber": "+91-8888"
}
I can recommend that you read the following article explaining what JSON is and how you use it: https://www.w3schools.com/js/js_json_intro.asp

In node.js how to extract uid from returned facebook providerData json array?

I've got my users signing in with facebook and that gets stored in firebase auth. In index.js i've got an onCreate function that stores some facebook related data in firestore.
When i log to cloud functions console event.data.providerData I get this:
[ { displayName: 'xxxx xxxxx',
photoURL: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p100x100/xxxxxxxxx_439xxx336xxxxxx.jpg?oh=bcxxxxxxxxxxx431ce&oe=xxxx4xxx3',
providerId: 'facebook.com',
uid: 'xxxxx725xxxxxx80' } ]
In my index.js file i've set this as
const providerData = event.data.providerData;
This always confuses me and i've read about it a lot.
These are my questions:
Is this a javascript object? Or a JSON object? Or a JSON array?
Does this need to be parsed? eg. JSON.parse(event.data.providerData)? What is JSON.parse actually doing?
To get access to the uid I have tried:
providerData[3]
providerData.uid
providerData["uid"]
providerData['uid']
JSON.parse(providerData) - and then all the above again
var obj = JSON.parse(providerData);
console.log( obj.uid );
I know there are plenty of posts out there re: similar topics and I think i've read a lot of them.
Thanks.
It's an array containing a JSON object at index 0.
The javascript interpreter is automatically parsing Valid JSON as a Javascript object.
Knowing that, you can now access directly the properties of your object like this:
providerData[0].displayName
providerData[0].photoURL
providerData[0].providerId
providerData[0].uid // <-- Your use case

How to get to request parameters in Postman?

I'm writing tests for Postman which in general works pretty easily. However, I now want to access some of the data of the request, a query parameter to be exact.
You can access the request URL through the "request.url" object which returns a String. Is there an easy way in Postman to parse this URL string to access the query parameter(s)?
The pm.request.url.query.all() array holds all query params as objects.
To get the parameters as a dictionary you can use:
var query = {};
pm.request.url.query.all().forEach((param) => { query[param.key] = param.value});
I have been looking to access the request params for writing tests (in POSTMAN). I ended up parsing the request.url which is available in POSTMAN.
const paramsString = request.url.split('?')[1];
const eachParamArray = paramsString.split('&');
let params = {};
eachParamArray.forEach((param) => {
const key = param.split('=')[0];
const value = param.split('=')[1];
Object.assign(params, {[key]: value});
});
console.log(params); // this is object with request params as key value pairs
edit: Added Github Gist
If you want to extract the query string in URL encoded format without parsing it. Here is how to do it:
pm.request.url.getQueryString() // example output: foo=1&bar=2&baz=3
pm.request.url.query returns PropertyList of QueryParam objects. You can get one parameter pm.request.url.query.get() or all pm.request.url.query.all() for example. See PropertyList methods.
It's pretty simple - to access YOUR_PARAM value use
pm.request.url.query.toObject().YOUR_PARAM
Below one for postman 8.7 & up
var ref = pm.request.url.query.get('your-param-name');
I don't think there's any out of box property available in Postman request object for query parameter(s).
Currently four properties are associated with 'Request' object:
data {object} - this is a dictionary of form data for the request. (request.data[“key”]==”value”) headers {object} - this is a dictionary of headers for the request (request.headers[“key”]==”value”) method {string} - GET/POST/PUT etc.
url {string} - the url for the request.
Source: https://www.getpostman.com/docs/sandbox
Bit late to the party here, but I've been using the following to get an array of url query params, looping over them and building a key/value pair with those that are
// the message is made up of the order/filter etc params
// params need to be put into alphabetical order
var current_message = '';
var query_params = postman.__execution.request.url.query;
var struct_params = {};
// make a simple struct of key/value pairs
query_params.each(function(param){
// check if the key is not disabled
if( !param.disabled ) {
struct_params[ param.key ] = param.value;
}
});
so if my url is example.com then the array is empty and the structure has nothing, {}
if the url is example.com?foo=bar then the array contains
{
description: {},
disabled:false
key:"foo"
value:"bar"
}
and my structure ends up being { foo: 'bar' }
Toggling the checkbox next to the property updates the disabled property:
have a look in the console doing :
console.log(request);
it'll show you all you can get from request. Then you shall access the different parameters using request., ie. request.name if you want the test name.
If you want a particular element in the url, I'm afraid you'll have to use some coding to obtain it (sorry I'm a beginner in javascript)
Hope this helps
Alexandre
Older post, but I've gotten this to work:
For some reason the debugger sees pm.request.url.query as an array with the items you want, but as soon as you try to get an item from it, its always null. I.e. pm.request.url.query[0] (or .get(0)) will return null, despite the debugger showing it has something at 0.
I have no idea why, but for some reason, it is not at index 0, despite the debugger claiming it is. Instead, you need to filter the query first. Such as this:
var getParamFromQuery = function (key)
{
var x = pm.request.url.query;
var newArr = x.filter(function(item){
return item != null && item.key == key;
});
return newArr[0];
};
var getValueFromQuery = function (key)
{
return getParamFromQuery(key).value;
};
var paxid = getValueFromQuery("paxid");
getParamFromQuery returns the parameter with the fields for key, value and disabled. getValueFromQuery returns just the value.

Categories

Resources