Problems with Parse json to retrieve the web page response - javascript

I have this web page response :
{"Status":"OK","RequestID":"xxxxxxxxxx","Results":[{"SubscriberKey":"teste132133","Client":null,"ListID":0,"CreatedDate":"0001-01-01T00:00:00.000","Status":"Active","PartnerKey":null,"PartnerProperties":null,"ModifiedDate":null,"ID":0,"ObjectID":null,"CustomerKey":null,"Owner":null,"CorrelationID":null,"ObjectState":null,"IsPlatformObject":false}],"HasMoreRows":false}
And I would like to just retrieve the SubscriberKey, like : "SubscriberKey":"teste132133"
So, I'm trying to use the Parse Json, but I believe that I'm doing something wrong that I don't know
follow the code :
<script language="javascript" runat="server">
Platform.Load("Core","1");
var response = HTP.Get("https://xxxxxxxx.pub.sfmc-content.com/vjpsefyn1jp"); //web page link
var obj = Platform.Function.ParseJSON(response);
Write(obj.Results[0].SubscriberKey)
</script>

I only know client side JavaScript, maybe this will work for you, it uses fetch to get the reponse, and then extracts the json value. It uses an asynchronous function call so we can use await to make the code more readible.
<script type="module">
async function getKey() {
const response = await fetch("https://xxxxxxxx.pub.sfmc-content.com/vjpsefyn1jp")
const json = await response.json()
const Results = json.Results
const key = Results[0].SubscriberKey
return key;
}
const key = await getKey();
console.log(`The key is: ${key}`);
</script>

Related

Calling API with Javascript html

What is the correct way to call this API? The api url is: https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd
I tried with this code
<p id="demo">
</p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.bitcoin;
}
};
xmlhttp.open("GET", "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd" + new Date().getTime(), true);
xmlhttp.send();
</script>
however the value I get is [object Object]. I want to get the value in "usd".
Where am I wrong? Thx
Replaces myObj with myObj.usd but returns null value
The API returns in the form of {"bitcoin":{"usd": -insert value here-}}, so you have to use myObj.bitcoin.usd
You need to access the usd part of the object when you set the innerHTML as #SuspenseFallback mentioned.
You also need to remove the + new Date().getTime() part from your URL string. I don't see a date part in the API docs for the price endpoint.
you should use the fetch method. the better and the modern way of calling API using native javascript.
There is no problem with the way you did it but there are a few things that you can do with fetch and not with XHR.
you can read more about fetch by this link: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
there is an example of using fetch:
fetch(
"https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd"
)
.then((response) => response.json())
.then((data) => {
console.log(data);
});
or you can use async-await to achieve the same result :
(async () => {
const response = await fetch(
"https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd"
);
const data = await response.json();
console.log(data);
})();
note: I have used Javascript Self Invoking Functions which is a
function that calls itself.
The answers quickly resolve the issue, however I ran into another problem where there are hyphenated words.
Sample API:
https://api.coingecko.com/api/v3/simple/price?ids=bitcoin-cash&vs_currencies=usd

how to access raw data in Postman(Request section)?

So I want to print out the client Name and the client Email as string values through the Postman console, but when I call the method I get a the array but with undefined values.
const res = pm.response.json();
const req = pm.request.toJSON();
let user = [req.body.raw.clientName, req.body.raw.clientName];
console.log(user);
Thank you very much!
You can get request body raw using:
pm.request.body.raw
For example:
You have request body in postman:
{
"foo": "bar"
}
You want to access value of foo in tab Tests:
const req = JSON.parse(pm.request.body.raw)
console.log(req.foo);

Data URI to JSON in Javascript?

I am facing a problem where my server app gets a JSON's DataURI and I would like to parse it into a JSON again. How could I do this? I tried different things but nothings seems to work. I tried simply parsing it or encodeURI(data); but still I can't get the original JSON.
This is the Data URI:
data:application/json;base64,ew0KICAgICJtYWx0X3R5cGUiOiAibG9nIiwNCiAgICAibWFsdF9kYXRhIjogIldvdywgdSByIGFsbW9zdCB0aGVyZSA6TyINCn0=
I tried this to encode it too:
var data = 'data:application/json;base64,ew0KICAgICJtYWx0X3R5cGUiOiAibG9nIiwNCiAgICAibWFsdF9kYXRhIjogIldvdywgdSByIGFsbW9zdCB0aGVyZSA6TyINCn0=';
Buffer.from(data.toString('utf8'), 'base64').toString('ascii')
But I get this if I log it on console: u+Zje F- J'm+k0P"&VGEwGR#"&Fvr"#P"&VGEvFF#"%vwrBR"FVw7BFW&R$r P'
The data URI is JSON encoded in Base64. There are two steps to this:
Decode the Base64 (for instance, with the atob function), and
Parse the resulting JSON
For instance (on a browser):
const dataURI = "data:application/json;base64,ew0KICAgICJtYWx0X3R5cGUiOiAibG9nIiwNCiAgICAibWFsdF9kYXRhIjogIldvdywgdSByIGFsbW9zdCB0aGVyZSA6TyINCn0=";
// 29 = length of "data:application/json;base64,"
const json = atob(dataURI.substring(29));
const result = JSON.parse(json);
console.log(result);
Your use of Buffer in your question suggests to me that you may be using Node.js. If so, you'd replace the call to atob with Buffer.from(data, 'base64').toString():
const dataURI = "data:application/json;base64,ew0KICAgICJtYWx0X3R5cGUiOiAibG9nIiwNCiAgICAibWFsdF9kYXRhIjogIldvdywgdSByIGFsbW9zdCB0aGVyZSA6TyINCn0=";
// 29 = length of "data:application/json;base64,"
const json = Buffer.from(dataURI.substring(29), "base64").toString();
const result = JSON.parse(json);
console.log(result);
If you don't mind changing the context into an asynchronous one you could use fetch() to parse the recourse. fetch() is normally used with URLs, but works with data URIs as well (in most browsers).
const dataURI = "data:application/json;base64,ew0KICAgICJtYWx0X3R5cGUiOiAibG9nIiwNCiAgICAibWFsdF9kYXRhIjogIldvdywgdSByIGFsbW9zdCB0aGVyZSA6TyINCn0=";
(async function () {
const response = await fetch(dataURI);
const data = await response.json();
console.log(data);
})();
If you are already using a library to simplify network requests, you could use them as well.
Examples:
jQuery:
const dataURI = "data:application/json;base64,ew0KICAgICJtYWx0X3R5cGUiOiAibG9nIiwNCiAgICAibWFsdF9kYXRhIjogIldvdywgdSByIGFsbW9zdCB0aGVyZSA6TyINCn0=";
(async function() {
const data = await $.getJSON(dataURI);
console.log(data);
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
axios:
const dataURI = "data:application/json;base64,ew0KICAgICJtYWx0X3R5cGUiOiAibG9nIiwNCiAgICAibWFsdF9kYXRhIjogIldvdywgdSByIGFsbW9zdCB0aGVyZSA6TyINCn0=";
(async function() {
const response = await axios.get(dataURI);
console.log(response.data);
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.0/axios.min.js"></script>

Can I apply jQuery on manually created document model?

I am trying to scrape some webpage, doing some searching I get to know about fetch API.
I have fetched a webpage using fetch() API from an URL , then I parsed the page into a DOM object, Now I have whole webpage in a DOM object. Can I apply jQuery functions on that?
my code
async function getProductData(url)
{
try {
const resp = await fetch(url);
var respText = await resp.text();
var parser = new DOMParser();
var doc = parser.parseFromString(respText, 'text/html')
// I am trying to do something like that. is it possible to do so ?
$(doc).ready( function(){
console.log( $( this) .find( $("#productTitle") ).text() );
});
}
catch (error) {
console.log(error);
}
}
.ready is not mandatory for me. I just need to extract some data from doc object. if there is any better way to fetch data from webpage please let me know, it would be very helpful for me.
Thank you so much.
You do not need and jQuery here:
const resp = await fetch(url);
const respText = await resp.text();
const parser = new DOMParser();
const doc = parser.parseFromString(respText, 'text/html');
console.log(doc.querySelector('#productTitle').innerText);

How to wait until GET request response

I try to create a html template which shows some Plotly graphs after fetch data from spesific URL with GET response.
It had to be very basic operation but it did not.
I can't able to stop java-script execution until the response return.
Internet suggest use async-await an I used:
<!DOCTYPE html>
<html>
<head>
<script>
function graphDrawFunction() {
var request = async () => {
var response = await fetch('http://127.0.0.1/log');
return await response.json();
}
var data = request();
for (let i=0;i<data.length;i++) {
// Some calculations generates traces and layouts from data for graphs
//var trace = function test1(data)
//var layout = function test2(data)
var section = document.getElementById('graphContainer');
var plotlyDiv = document.createElement("div");
plotlyDiv.id = "graph" + String(Math.random());
section.appendChild(plotlyDiv);
Plotly.plot(plotlyDiv.id, trace, layout);
}
return "--"
};
</script>
</head>
<body onload="graphDrawFunction();">
<h1>Report</h1>
<div id="graphContainer">**********</div>
</body>
</html>
This thing not works because async not return response.json() as I expected.
So I did different thing:
function graphDrawFunction() {
var request = async () => {
var response = await fetch('http://127.0.0.1/log');
var data = await response.json();
for (let i=0;i<data.length;i++) {
// Some calculations generates traces and layouts from data for graphs
//var trace = function test1(data)
//var layout = function test2(data)
var section = document.getElementById('graphContainer');
var plotlyDiv = document.createElement("div");
plotlyDiv.id = "graph" + String(Math.random());
section.appendChild(plotlyDiv);
Plotly.plot(plotlyDiv.id, trace, layout);
}
return "--"
}
};
But this did not work too.
So I need help.
More info about project:
My goal is creating a report program. User can filter data and create reports from data. I use Plotly Dash and Flask.
First, Python-Dash fetch the data from SQL. The user then filters the data with a few buttons provided by Dash. This is happening on Python side. Then Flask serve the data on http://127.0.0.1/log. So anything that want to use the data just need to send GET request.
When user click to the create report button a new tab opened with the template I wrote above. You know the story after this.
If there is more appropriate way to do this feel free to say
I don't know much about Web programming
Thank you for reading.
try like this
async function graphDrawFunction() {
var request = async () => {
var response = await fetch('http://127.0.0.1/log');
return response.json();
}
var data = await request();
for (let i=0;i<data.length;i++) {
// Some calculations generates traces and layouts from data for graphs
//var trace = function test1(data)
//var layout = function test2(data)
var section = document.getElementById('graphContainer');
var plotlyDiv = document.createElement("div");
plotlyDiv.id = "graph" + String(Math.random());
section.appendChild(plotlyDiv);
Plotly.plot(plotlyDiv.id, trace, layout);
}
return "--"
};
Take a look to the documentation of fetch api: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch.
The await is just to wait for the response, once response is set, you should be able to access it in response.json() like this:
<!DOCTYPE html>
<html>
<head>
<script>
function graphDrawFunction() {
var request = async () => {
var response = await fetch('http://127.0.0.1/log');
return response.json();
}
var data = request();
for (let i=0;i<data.length;i++) {
// Some calculations generates traces and layouts from data for graphs
//var trace = function test1(data)
//var layout = function test2(data)
var section = document.getElementById('graphContainer');
var plotlyDiv = document.createElement("div");
plotlyDiv.id = "graph" + String(Math.random());
section.appendChild(plotlyDiv);
Plotly.plot(plotlyDiv.id, trace, layout);
}
return "--"
};
</script>
</head>
<body onload="graphDrawFunction();">
<h1>Report</h1>
<div id="graphContainer">**********</div>
</body>
</html>
Using your first example:
Since request is an async function, unless you call it with await, it will run asynchronously.
Therefore, graphDrawFunction() can be written like this:
function graphDrawFunction() {
var data = (await fetch('http://127.0.0.1/log')).json();
for (let i=0;i<data.length;i++) {
// ....
}
return "--"
};

Categories

Resources