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

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'])

Related

How to get a value from JSONObject in NodeJS?

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

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

Dots in snekfetch request are causing a problem

I'm trying to get data from a json file with snekfetch for my discord bot but I have a problem...
This is a part of the json file
"nodes":{
"main.c10":{
"online":1624,
"inbattles":829
},
If I want to get "online" number I should write this
var c10 = r.body.nodes.main.c10.online;
but with the dot after main is interpreting the request like this:
"nodes":{
"main {
.c10":{
"online":1624,
"inbattles":829
}
},
How I can solve this problem?
You can access that property with square brackets:
var c10 = r.body.nodes['main.c10'].online;
Edit in response to comments:
In this case r.body is a buffer, and so you need to first convert it to an object, only then you can access its properties like .nodes. You can find a working demo here.
JSON.parse(r.body.toString()).nodes['main.c10'].online

Reading a JSON response in Javascript

I'm making an ajax post request to a super simple python function that takes a student's name and spits out a url that corresponds to it. Currently, the Python function passes this back in json and looks like so when console.log(JSON.stringify(response)) is called:
{"readyState":4,"responseText”:”\ {\”studentURL\”: \”https://prepacademy.jackjohnson.com\”} ”,”responseJSON”: {“studentURL”:”https://prepacademy.jackjohnson.com”},”status":200,"statusText":"OK"}
I was wondering how do I take this larger chunk of information and filter it so that I would only get the https://prepacademy.jackjohnson.com part?
response is a JavaScript Object of which you can access the properties using either Dot-notation or bracket-notation, like so:
let response = {
"readyState": 4,
"responseText": "\ {\"studentURL\": \"https://prepacademy.jackjohnson.com\"} ",
"responseJSON": {
"studentURL": "https://prepacademy.jackjohnson.com"
},
"status": 200,
"statusText": "OK"
};
// dot-notation
console.log(response.responseJSON.studentURL)
// bracket-notation (allows for computed paths)
console.log(response["responseJSON"]["studentURL"])
response.responseJSON.studentURL

API Connect - 500 error when including basic Javascript

I'm trying some basic API Connect tutorials on IBM's platform (running locally using loopback) and have got completely stuck at an early point.
I've built a basic API service with some in-memory data and setter / getter functions. I've then built a separate API which takes two GET parameters and uses one of my getter functions to perform a search based on two criteria. When I run it, I successfully get a response with the following JSON object:
[{"itemId":1,"charge":9,"itemSize":2,"id":2}]
I've then tried to add a piece of server logic that modifies the response data - at this point, I'm just trying to add an extra field. I've added a Javascript component in the Assemble view and included the following code (taken from a tutorial), which I thought should modify the message body returned by the API while still passing it through:
//APIC: get the payload
var json = apim.getvariable('message.body');
//console.error("json %s", JSON.stringify(json));
//same: code to inject new attribute
json.platform = 'Powered by IBM API Connect';
//APIC: set the payload
//message.body = json;
apim.setvariable('message.body', json);
Instead of getting an extra JSON parameter ("platform"), all I get is a 500 error when I call the service. I'm guessing that I'm doing something fundamentally wrong, but all the docs suggest these are the right variable names to use.
You can't access json.platform but at that point json variable is json type. Are you sure that you can add a property to a json type variable if your json object lacks of that property? I mean: What if you first parse the json variable of json type to a normal object, then add new property, and finally stringify to json type again for body assigning purposes?
var json = JSON.parse(apim.getvariable('message.body')); //convert to normal object
json.platform = 'Powered by IBM API Connect'; //add new property
apim.setvariable('message.body', JSON.stringify(json)); //convert to json again before setting as body value
You need to get the context in some determined format, and in this function do your logic. For example if your message is in json you need to do:
apim.readInputAsJSON(function (error, json) {
if (error)
{
// handle error
apim.error('MyError', 500, 'Internal Error', 'Some error message');
}
else
{
//APIC: get the payload
var json = apim.getvariable('message.body');
//console.error("json %s", JSON.stringify(json));
if(json){
//same: code to inject new attribute
json.platform = 'Powered by IBM API Connect';
//APIC: set the payload
//message.body = json;
apim.setvariable('message.body', json);
}
}
});
Reference:
IBM Reference
You have the message.body empty, put a invoke/proxy policy before your gateway/javascript policy for example.

Categories

Resources