reading output of API in react - javascript

I am calling one API in react. for that I am getting output in below format.
{
"first_page_uri": "/2010-04-01/Accounts/xxxxxxxxxxxxxxxxx/Messages.json?PageSize=50&Page=0",
"end": 49,
"previous_page_uri": null,
"messages": [
{
"body": "",
"num_segments": "1",
"direction": "outbound-api",
"from": "+12058557185",
"date_updated": "Mon, 29 Aug 2022 09:07:47 +0000",
"price": "-0.04410",
"error_message": null,
"uri": "/2010-04-01/Accounts/xxxxxxxxxxxxxxxxx/Messages/xxxxxxxxxxxxxxxxx.json",
"account_sid": "xxxxxxxxxxxxxxxxx",
"num_media": "0",
"to": "+919823772514",
"date_created": "Mon, 29 Aug 2022 09:07:42 +0000",
"status": "delivered",
"sid": "SMfa2e62cf71761db915657b02605bc689",
"date_sent": "Mon, 29 Aug 2022 09:07:43 +0000",
"messaging_service_sid": "xxxxxxxxxxxxxxxxx",
"error_code": null,
"price_unit": "USD",
"api_version": "2010-04-01",
"subresource_uris": {
"media": "/2010-04-01/Accounts/xxxxxxxxxxxxxxxxx/Messages/xxxxxxxxxxxxxxxxx/Media.json",
"feedback": "/2010-04-01/Accounts/xxxxxxxxxxxxxxxxx/Messages/xxxxxxxxxxxxxxxxx/Feedback.json"
}
},
{
"body": "",
"num_segments": "1",
"direction": "outbound-api",
"from": "+12058557185",
"date_updated": "Mon, 29 Aug 2022 05:51:57 +0000",
"price": "-0.04410",
"error_message": null,
"uri": "/2010-04-01/Accounts/xxxxxxxxxxxxxxxxx/Messages/xxxxxxxxxxxxxxxxx.json",
"account_sid": "AC9ab9e25e89eaa96c474e9a39867bb2f3",
"num_media": "0",
"to": "+919823772514",
"date_created": "Mon, 29 Aug 2022 05:51:47 +0000",
"status": "delivered",
"sid": "SM5237fb62ff472b5e124fdd2ea073fffe",
"date_sent": "Mon, 29 Aug 2022 05:51:47 +0000",
"messaging_service_sid": "MG00d095919337aa95aeb5b74c8f0bd81c",
"error_code": null,
"price_unit": "USD",
"api_version": "2010-04-01",
"subresource_uris": {
"media": "/2010-04-01/Accounts/xxxxxxxxxxxxxxxxx/Messages/xxxxxxxxxxxxxxxxx/Media.json",
"feedback": "/2010-04-01/Accounts/xxxxxxxxxxxxxxxxx/Messages/xxxxxxxxxxxxxxxxx/Feedback.json"
}
},
{
"body": "",
"num_segments": "1",
"direction": "outbound-api",
"from": "+12058557185",
"date_updated": "Mon, 29 Aug 2022 05:24:09 +0000",
"price": "-0.04410",
"error_message": null,
"uri": "/2010-04-01/Accounts/xxxxxxxxxxxxxxxxx/Messages/xxxxxxxxxxxxxxxxx.json",
"account_sid": "xxxxxxxxxxxxxxxxx",
"num_media": "0",
"to": "+919727930925",
"date_created": "Mon, 29 Aug 2022 05:24:05 +0000",
"status": "delivered",
"sid": "SM1528c06455368cfb7e00ab8283ed773c",
"date_sent": "Mon, 29 Aug 2022 05:24:05 +0000",
"messaging_service_sid": "MG00d095919337aa95aeb5b74c8f0bd81c",
"error_code": null,
"price_unit": "USD",
"api_version": "2010-04-01",
"subresource_uris": {
"media": "/2010-04-01/Accounts/xxxxxxxxxxxxxxxxx/Messages/xxxxxxxxxxxxxxxxx/Media.json",
"feedback": "/2010-04-01/Accounts/xxxxxxxxxxxxxxxxx/Messages/xxxxxxxxxxxxxxxxx/Feedback.json"
}
}
,`
I want to read differnet fields on it to perform some operation in UI.
for example I want to read status, body, from etc.
alert("Message is:"+JSON.stringify(response.data))
this line is giving output of an API properly.
but when I write
alert("Message is:"+JSON.stringify(response.data.messages))
alert("Message is:"+JSON.stringify(response.data.messages.from))
alert("Message is:"+JSON.stringify(response.data.messages[0].from))
I am getting undefined and exceptions. my goal is to print the value in UI for specific status.
Can somrebody help me on that.
I tried lot of options and googling but nothing helped. I am new to javascript

Now this is a relatively complex topic for a beginner, let's start at the beginning.
Objects
What you get from the api request is an object. An object has properties, like first_page_uri, end, and so on. In JSON that will look like this:
{
"first_page_uri": "this is a value",
"end": 42
}
If you parsed the json string to a javascript object, like I assume you already have. You will have your object handle / variable. In your case that should be response.data.
With that handle you are able to get those object properties by accessing them using . after the handle and their name. For example you can display first_page_uri by writing this:
alert(response.data.first_page_uri)
Lists (Arrays)
Inside the response, there is a list. A list in JSON is represented like this:
"my_list": [
"a",
"b",
"c"
]
In this case the list has 3 values containing the strings a, b and c.
If you have a list in javascript, to get any of the values you can do the following:
alert(my_list[index])
Where my_list is the list and index is a value between 0 for the first element a and in this case 2 for the last element c.
Caution: we start counting from 0.
To show b in an alert we would write:
alert(my_list[1])
Combination of both
The attribute messages in your response is such a list. It contains not strings, but objects. Like so:
{
"messages": [
{
"body": "this is a message"
},
{
"body": "this is another message"
}
]
}
In this case if you wanted to retrieve the first message body and alert it, you would need to combine both patterns from above:
alert(response.body.messages[0].body)
I am assuming your object is in response.body. We are accessing messages and then selecting the first with [0] and then selecting body from that message.
Possible solutions
The problems you are encountering are probably the following:
alert is only able to show simple data types like string, number and so on. So trying to print out a whole list for example will not work.
I assume your other code is correct by the fact that you say that:
alert("Message is:"+JSON.stringify(response.data))
works.
All you would need to do to fix your code, is to remove the second line:
alert("Message is:"+JSON.parse(response.data.messages.from))
.from makes js try to access a property of a list. As discussed above. Objects have properties, lists do not. So react throws an exception.
Your other lines:
alert("Message is:"+JSON.stringify(response.data.messages))
alert("Message is:"+JSON.stringify(response.data.messages[0].from))
should work. As they seem to be correct.
The UI
Now regarding the UI part you are talking about...
If you are inside a react component, which would probably look somewhat like this:
const ComponentName = (/* maybe stuff here */) => {
// maybe a lot of stuff here
return (
/* this is the interesting part */
)
}
You want to be looking for the return part.
Inside there you can write HTML-like code. A simple UI output to show all messages would be:
const ComponentName = () => {
// here you do your api stuff so you get the response variable
const response;
return (
<>
<h1>All messages:</h1>
{
response.body.messages.map((message) => (
<p>{message.body}</p>
))
}
</>
)
}
I did use a new thing here: the map function on a list. I put it in the recommended reading section below.
The part in the middle:
<h1>All messages:</h1>
{
response.body.messages.map((message) => (
<p>{message.body}</p>
))
}
Is the important part. You can more or less put it anywhere in the return statement and it should show up.
Recommended reading
To learn more you probably want to look up the following things:
Arrays
Array (map function)
Object (literals)
React (quick start tutorial)
My thoughts (please ignore if unsuited)
If you are very new to javascript and this is a free time project. I would recommend taking it a step slower. While I do not want to discourage you from continuing with what you are doing, I assume that you can learn quicker and more effectively by stepping back and for example start with a HTML, CSS and JS only project without libraries. That should make you more comfortable in the concepts involved before jumping into a more complicated project. Especially if you do not have much or any experience with other languages.
A good start for that would be this project. It does include jQuery, but you do not need to use it.
I wish you the best of luck going forward!

You should use JSON.parse instead of JSON.stringify.
JSON.parse convert json string to js object and JSON.stringify do the reversed job.
So, your code should look like:
alert("Message is:"+JSON.parse(response.data.messages))
alert("Message is:"+JSON.parse(response.data.messages.from))
alert("Message is:"+JSON.parse(response.data.messages[0].from))
One more note here, to access nested property in JS object and avoid access anything from undefined, you should use JS optional chaining feature like below:
alert("Message is:"+JSON.parse(response?.data?.messages))
alert("Message is:"+JSON.parse(response?.data?.messages?.from))
The ? take care of null check for you.

Try this, but first replace this api with your api
import React from 'react';
import './style.css';
class App extends React.Component {
constructor() {
super();
this.state = {
data: null,
};
}
componentDidMount() {
fetch('https://reqres.in/api/users') // replace this api with your api
.then((response) => {
response.json().then((result) => {
console.warn(result.data);
this.setState({ data: result.data });
});
});
}
render() {
return (
<div>
{this.state.data
? this.state.data.map((item, i) => (
<div>
<p>
{i} --- {item.body} {item.from}{' '}
</p>
</div>
))
: null}
</div>
);
}
}
export default App;

Related

Oracle Apex send an Calender Invite as an Appointment not ICS attachment

I would like to send a calendar invitation via Oracle Apex.
There are already many tutorials explaining how to send the calendar entry as an ICS attachment. In my case I would like to try that the recipient receives a direct invitation.
So far I have used the APEX_MAIL extension.
Here is a part of the Code i use: (That is the way i can send the Appointment as ICS Attatchment)
if l_body is not null then
l_mail_id := apex_mail.send(
--p_to => rec.creator_email,
p_to => t_an_liste,
p_cc => '',
p_bcc => '',
--p_bcc => '',
p_from => 'noreply#Sample.com',
p_body => l_body,
p_body_html => l_body,
p_subj => l_title);
if rec.SHOP_name is not null then
if rec.HYPERLINK Like '%teams.microsoft.com%' then
v_location := 'Microsoft Teams-Besprechung';
else
v_location := rec.HYPERLINK;
end if;
l_cal_1 := APEX_MAIL_CALENDAR('Terminbuchung ('||rec.SHOP_name||')',l_body,rec.TS_OPEN,rec.TS_CLOSE,v_location,15,'N');
apex_mail.add_attachment (p_mail_id => l_mail_id,
p_attachment => l_cal_1,
p_filename => 'Termineintrag.ics',
--Name of the ICS file
p_mime_type => 'application/hbs-ics'
);
end if;
APEX_MAIL.PUSH_QUEUE;
end if;
Does anyone know a solution for my problem?
Thank you!
Lukas :)
If you are using Microsoft 365, simplest way would probably be to use the Microsoft Graph API to Create an Event. You can pass all of the information about the "event" in the meeting invite in the body of your API request (see example below).
You will need to set up the proper access in Microsoft 365 so that you can authenticate before you can use the API. You will also need to designate an owner for the event using /me/ in the API call or using /users/{id | userPrincipalName}/ if you have the access set up properly.
{
"subject": "Let's go for lunch",
"body": {
"contentType": "HTML",
"content": "Does noon work for you?"
},
"start": {
"dateTime": "2017-04-15T12:00:00",
"timeZone": "Pacific Standard Time"
},
"end": {
"dateTime": "2017-04-15T14:00:00",
"timeZone": "Pacific Standard Time"
},
"location":{
"displayName":"Harry's Bar"
},
"attendees": [
{
"emailAddress": {
"address":"samanthab#contoso.onmicrosoft.com",
"name": "Samantha Booth"
},
"type": "required"
}
],
"allowNewTimeProposals": true,
"transactionId":"7E163156-7762-4BEB-A1C6-729EA81755A7"
}

Using Jsoniq to display some of the string in json

Can you guys teach me on how to use jsoniq to display both of the book name which is robin cruose and tom jones? i've gone through some research but no matter how i do, it's always wrong.
{
"books": {
"reader": {
"Read": {
"book": {
"name": "Robinson Crusoe",
"author": "Daniel Defoe"
}
},
"HaventRead": {
"book": {
"name": " Tom Jones",
"author": "Henry Fielding "
}
},
"_type": "Ken Rawing"
}
}
}
This is how i did in zorba.io and it got lots of error, i am very sure the way i did is totally wrong. Please teach me
for $reader in collection("books"),
$read in collection("books"),
$book in collection ("books")
where $reader.type eq "Ken Rawing"
return $book
Getting some leaf values from a JSON document is done with the navigation syntax, which is the . notation.
It doesn't need a for clause, as iteration is implicit with the ..
Assuming the object is stored in the variable $content, $content.books.reader navigates to the object with the fields Read and HaventRead. Calling jnlib:values() then gets the two objects in there, and then one continues all the way to the name with .book.name.
The query is like so (most of it is actually the input document itself, which is typically stored in a file or a data store instead):
jsoniq version "1.0";
import module namespace jnlib = "http://jsoniq.org/function-library";
(: That's the input document, stored in a global variable :)
declare variable $content := {
"books": {
"reader": {
"Read": {
"book": {
"name": "Robinson Crusoe",
"author": "Daniel Defoe"
}
},
"HaventRead": {
"book": {
"name": " Tom Jones",
"author": "Henry Fielding "
}
},
"_type": "Ken Rawing"
}
}
};
(: That's the query :)
jnlib:values($content.books.reader).book.name
Mind the jsoniq version="1.0";, which activates the native JSONiq parser (the default parser on try.zorba.io is XQuery).
It can also be tested in zorba.io
Note
JSONiq also exists as an extension to XQuery, in which case navigation is done with function calls, as the . is a valid character in XML names. However, it is not recommended to use this unless you have XML to deal with as well.
jnlib:values($content("books")("reader"))("book")("name")

Twilio PHP API how to get message timestamp DateSent?

I have this code block iterating through the Twilio Message list.. but I keep getting null for DateSent (or DateCreated), I'm looking to get bakc the timestamp of the message. Everything else (the other fields , from, to , body all work fine)
$client = new Services_Twilio($twilio['sid'],$twilio['token']);
// Loop over the list of messages echo each key property
foreach ($client->account->messages as $message) {
$list_sms_messages[]=array('timestamp'=>$message->dateSent,
'from'=>$message->from ,
'to'=>$message->to,
'body'=> $message->body );
}
According to the API DateSent or (DateCreated) should be in the message list object. Any ideas
I've come across this issue myself. Seeing as you're using the PHP library I can try resolve this issue for you. In this section:
// Loop over the list of messages echo each key property
foreach ($client->account->messages as $message) {
$list_sms_messages[]=array(
'timestamp'=>$message->dateSent,
'from'=>$message->from ,
'to'=>$message->to,
'body'=> $message->body
);
}
The $message->dateSent is actually a PHP DateObject so you can fetch the timestamp in Epoch format by change it to: $message->dateSent->getTimestamp()
The returned timestamp can then be formatted with the date() function.
I hope this helps.
I figured it out by poking around TWILIO site examples, it turns out that their API guide for their TWIL formatted JSON ( and XML) uses different property names than their TWILIO-PHP wrapper library.. Here's the typical Message JSON when using the PHP library ( i omitted some fields for privacy reasons), but as you can see:
DateSent is actually date_sent ,
DateCreated is actually date_created and so on..
Once I plugged that into my code it worked as expected...
"messages": [{
"sid": "SM37e1d0d26f2ac513fbb30024a10e98fc",
"date_created": "Thu, 19 Mar 2015 20:14:22 +0000",
"date_updated": "Thu, 19 Mar 2015 20:14:22 +0000",
"date_sent": "Thu, 19 Mar 2015 20:14:22 +0000",
"account_sid": "AC2a0f5850342e7c43785ab72742e0bec0",
"to": "+17324918525",
"from": "+19733438312",
"body": "Si",
"status": "received",
"num_segments": "1",
"num_media": "0",
"direction": "inbound",
"api_version": "2010-04-01",
"price": "-0.00750",
"price_unit": "USD",
"error_code": null,
"error_message": null,
}]

accessing mongodb's object from mapper (MapReduce)

I have an extra question based on the one I asked before:
calculate frequency using mongodb aggregate framework
so my data in MongoDB looks like this now:
{
"data": {
"interaction": {
"created_at": "Wed, 09 Apr 2014 14:38:16 +0000"
}
},
"_id": {
"$oid": "53455b59edcd5e4e3fdd4ebb"
}
}
before I used to have it like:
[
{
created_at: "2014-03-31T22:30:48.000Z",
id: 450762158586880000,
_id: "5339ec9808eb125965f2eae1"
}
]
so to access created_at I was using mapper like:
var mapper = function () {
if ( this.created_at.getTime() > ( last_date + 10000 ) ) {
...
but as the structure in my database has changed, I tried to change:
this.created_at.getTime()
to:
this.data.interaction.created_at.getTime()
but unfortunately it didn't work out. Thank you for any help
Hate to make this that simple but all you want to do when importing these date strings is this:
new Date("Wed, 09 Apr 2014 14:38:16 +0000")
Which will return a proper date type that you actually should be inserting as part of your data.

EventBrite API event_search return incorrect date

I'm querying EventBrite with JavaScript/jQuery using the code below. It pulls the correct events, but the time is always 6:45am regardless of the event's actual time. Any ideas of what I'm doing wrong?
// <script> included in <head>
http://evbdn.eventbrite.com/s3-s3/static/js/platform/Eventbrite.jquery.js
// external JS file, loaded after above script
$(document).ready(function(){
Eventbrite({'app_key': "__ValidKey__"}, function(eb){
var options = { 'date':"Future",'organizer': "Lamplighters International", "sort_by":"date" };
eb.event_search( options, function( response ){
$("#upcomingEvents").html(eb.utils.eventList( response, eb.utils.eventListRow ));
console.log( $("#upcomingEvents").html() );
[ ... ]
One of the events returned displays this (formatted for clarity):
<div class="eb_event_list_item" id="evnt_div_8625628487">
<span class="eb_event_list_title">
W100 - Basic Training Workshop
</span>
<span class="eb_event_list_date">Wed Mar 19 2014</span>
<span class="eb_event_list_time">6:45am</span>
<span class="eb_event_list_location">Lamplighters International</span>
</div>
The event should show 11:45am. Here's the EventBrite page: http://www.eventbrite.com/e/w100-basic-training-workshop-tickets-8625628487?aff=SRCH
Hmmm.... I just replicated your code, and it looks like the eb.utils.eventListRow is spitting out the wrong time. The API is returning the correct start_date value.
My suggestion is to parse the JSON results yourself. Instead of using eb.utils.eventListRow you can get the eb.event_search response as a JSON object:
function getEventbriteEvents() {
Eventbrite({'app_key': "54XIQ35B73N6UXADDF", 'user_key':"12922547909277245491"}, function(eb){
eb.event_search( {'date':"Future",'organizer': "Lamplighters International", "sort_by":"date"}, function( response ){
console.log(response);
});
});
}
The response variable will be a JSON object with structure shown here (full result structure in the docs: http://developer.eventbrite.com/doc/events/event_search/):
{
"events": [{
"summary": {
"total_items": 6,
"first_event": 8625730793,
"last_event": 8648687457,
"filters": {
"organizer": "Lamplighters International"
},
"num_showing": 6
}
},
{
"event": {
"timezone": "America/Chicago",
"id": 8625730793,
"title": "W100 - Basic Training Workshop",
"start_date": "2014-04-09 11:45:00",
"end_date": "2014-04-09 13:00:00",
"timezone_offset": "GMT-0500",
[...tons more event info...]
}
},
{[...more events...]}
}
Hope that helps you out. Good luck!

Categories