I am trying to built chatbot that fetches json response from api.ai. I need to display messages part from below json response.
{
"id": "ae66f8e4-a047-478a-8108-8b0147610f18",
"timestamp": "2017-09-28T05:02:03.552Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "hi",
"action": "",
"actionIncomplete": false,
"parameters": {},
"contexts": [],
"metadata": {
"intentId": "d2f3c8bd-fc1b-4b6b-9d3d-08b6be93364e",
"webhookUsed": "false",
"webhookForSlotFillingUsed": "false",
"intentName": "greetings"
},
"fulfillment": {
"speech": "Hi.Please enter your query.",
"messages": [
{
"type": 0,
"speech": "Hi.Please enter your query."
}
]
},
"score": 1
},
"status": {
"code": 200,
"errorType": "success"
},
"sessionId": "saurabh"
}
Below is the sample piece of code, but it is unable to fetch speech from messages part in spokenResponse variable.
function prepareResponse(val) {
var debugJSON = JSON.stringify(val,undefined, 2);
var spokenResponse = val.messages.speech;
respond(spokenResponse);
debugRespond(debugJSON);
}
I get below error:
script.js:33 Uncaught TypeError: Cannot read property 'speech' of undefined
at prepareResponse (script.js:33)
at Object.success (script.js:21)
at i (jquery-3.2.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-3.2.1.min.js:2)
at A (jquery-3.2.1.min.js:4)
at XMLHttpRequest.<anonymous> (jquery-3.2.1.min.js:4)
However, when I try to fetch source from result part it fetches correctly.
var spokenResponse = val.result.source;
I am new to ajax and Json, Kindly help.
You have to access messages via the fulfillment property. Note that messages contains an array of objects, so in order to get to the speech property of the first object, you have to access the object in the first index.
var spokenResponse = val.fulfillment.messages[0].speech;
If you wanted to iterate through all messages (assuming you have more than one message):
var messageArr = val.fulfillment.messages;
var speechArr = [];
for (var i = 0; i < messageArr.length; i++) {
speechArr.push(messageArr[i].speech);
}
This will give you an array of speech messages.
Related
Vijay Anand asked this question yesterday, but it was closed before he got an answer:
HTTP Response:
{
"entry": {
"#xml:base": "https://API_PROC_SRV/",
"#xmlns": "http://www.w3.org/2005/Atom",
"#xmlns:m": "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata",
"#xmlns:d": "http://schemas.microsoft.com/ado/2007/08/dataservices",
"id": "https://API_PROC_SRV/A_Order",
"title": {
"#type": "text",
"#text": "A_Order()"
},
"updated": "2020-02-29T07:33:28Z",
"category": {
"#term": "Type",
"#scheme": "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"
},
"link": [],
"content": {
"#type": "application/xml",
"m:properties": {
"d:Order": "123456789"
}
}
}
}
Javascript code:
var json = response;
var order = json.object.entry.content['m:properties']['d:Order']; // I intend to read Order no from the below response.
Error (example, jsbin.com):
"TypeError: Cannot read property 'entry' of undefined
at null.js:27:25
at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:13924
at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:10866"
Per JSLint, the response is valid JSON.
json.object.entry is obviously wrong ... but
Q: What is the correct Javascript syntax to access the "order" value (named d:Order), when m:properties and d:Order both have semicolons in the name?
PS: I nominated Vijay's original question for re-opening ... but I'm not optimistic. Hence my new question.
You need to parse the JSON. And there's no object property anywhere, it's jut json.entry.content.
response = `{
"entry": {
"#xml:base": "https://API_PROC_SRV/",
"#xmlns": "http://www.w3.org/2005/Atom",
"#xmlns:m": "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata",
"#xmlns:d": "http://schemas.microsoft.com/ado/2007/08/dataservices",
"id": "https://API_PROC_SRV/A_Order",
"title": {
"#type": "text",
"#text": "A_Order()"
},
"updated": "2020-02-29T07:33:28Z",
"category": {
"#term": "Type",
"#scheme": "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"
},
"link": [],
"content": {
"#type": "application/xml",
"m:properties": {
"d:Order": "123456789"
}
}
}
}`;
var json = JSON.parse(response);
var order = json.entry.content['m:properties']['d:Order'];
console.log(order);
When I try to parse this JSON (Discord webhook):
{
"content": "this `supports` __a__ **subset** *of* ~~markdown~~ 😃 ```js\nfunction foo(bar) {\n console.log(bar);\n}\n\nfoo(1);```",
"embed": {
"title": "title ~~(did you know you can have markdown here too?)~~",
"description": "this supports [named links](https://discordapp.com) on top of the previously shown subset of markdown. ```\nyes, even code blocks```",
"url": "https://discordapp.com",
"color": 16324973,
"timestamp": "2018-12-18T09:22:12.841Z",
"footer": {
"icon_url": "https://cdn.discordapp.com/embed/avatars/0.png",
"text": "footer text"
},
"thumbnail": {
"url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"image": {
"url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"author": {
"name": "author name",
"url": "https://discordapp.com",
"icon_url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"fields": [
{
"name": "🤔",
"value": "some of these properties have certain limits..."
},
{
"name": "😱",
"value": "try exceeding some of them!"
},
{
"name": "🙄",
"value": "an informative error should show up, and this view will remain as-is until all issues are fixed"
},
{
"name": "<:thonkang:219069250692841473>",
"value": "these last two",
"inline": true
},
{
"name": "<:thonkang:219069250692841473>",
"value": "are inline fields",
"inline": true
}
]
}
}
Using this code:
var parsed = JSON.parse(req.body)
I get this error:
SyntaxError: Unexpected token o in JSON at position 1
But if I use a website such as
https://jsonformatter.curiousconcept.com
To validate the JSON, it says the JSON is valid.
What is wrong here?
UPDATE
I'm using an express server to simulate discord server, so it sends web hooks to the express server instead, I get the JSON using req.body.
This happens because JSON is a global object (it's the same object where you read the method parse!), so when you invoke JSON.parse(JSON) javascript thinks you want to parse it.
The same thing doesn't happen when you pass the variable to the validator, because it will be assigned to a local variable:
let JSON = "{}";
validate(JSON);
function(x) {
JSON.parse(x); // here JSON is again your global object!
}
EDIT
According to your updated question, maybe it happens because you already use bodyParser.json() as middleware, and when you use it, req.body is already an object and you don't need to parse it again.
Trying to parsing an already parsed object will throw an error.
It would be something like without using JSONStream:
http.request(options, function(res) {
var buffers = []
res
.on('data', function(chunk) {
buffers.push(chunk)
})
.on('end', function() {
JSON.parse(Buffer.concat(buffers).toString())
})
})
For using it with JSONStream, it would be something like:
http.request(options, function(res) {
var stream = JSONStream.parse('*')
res.pipe(stream)
stream.on('data', console.log.bind(console, 'an item'))
})
(OR)
Here is the Some Steps for this issue..
You Can use lodash for resolving this.
import the lodash and call unescape().
const _ = require('lodash');
let htmlDecoder = function(encodedStr){
return _.unescape(encodedStr);
}
htmlDecoder(JSON);
I have a problem to extract a data from a json file created from a GET from Imgur API.
That is the json :
{
"id": "ADgvagy",
"title": "This game is so much fun ",
...
"include_album_ads": false,
"images": [
{
"id": "VLeeDfj",
...
"in_gallery": false,
"link": "https://i.imgur.com/VLeeDfj.mp4",
"mp4_size": 2707912,
"mp4": "https://i.imgur.com/VLeeDfj.mp4",
"gifv": "https://i.imgur.com/VLeeDfj.gifv",
"hls": "https://i.imgur.com/VLeeDfj.m3u8",
"processing": {
"status": "completed"
},
"comment_count": null,
...
"score": null
}
]
},
I have no problem to extract the title data when I do this.props.post.title.
I tried :
this.props.post.images.link -> TypeError: undefined is not an object (evaluating 'this.props.post.images.link')
this.props.post.images[0].link -> TypeError: undefined is not an object (evaluating 'this.props.post.images[0]')
Thanks for your time.
I found it. The correct way is to do this.props.post["images"][0].link
This question already has answers here:
Access-Control-Allow-Origin error sending a jQuery Post to Google API's
(7 answers)
Closed 8 years ago.
I'm trying to fetch and parse json data so I could output it to a blank HTML file. The problem that keeps occurring to me is that if I fetch the data and parse it I get a Uncaught TypeError: Cannot read property 'SOCENGPRE' of undefined error. If I fetch the json data in dataType: "text" format I get the XMLHttpRequest cannot load <api url> No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. error. The website is on a local machine and I cannot edit the server to be cross-platformed because of person reasons. The code looks like this :
var myDataVar;
function main() {
$.ajax({
url: "http://api&leagues=SOCENGPRE&format=jsonp&callback=?",
dataType: "json",
success: function (data) {
myDataVar = $.parseJSON(data);
getUpcomingFixtures();
}
});
}
function getUpcomingFixtures() {
for (var i = 0; i <= myDataVar.SOCENGPRE.fixtures.length - 1; i++) {
console.log(myDataVar.SOCENGPRE.fixtures[i].id);
console.log(myDataVar.SOCENGPRE.fixtures[i].home_team + " vs " + myDataVar.SOCENGPRE.fixtures[i].away_team);
}
}
An example of the data being fetched looks like this :
{
"SOCENGPRE": {
"league_name": "Barclays Premier League",
"league_phid": null,
"league_type": null,
"fixtures": [{
"id": "64714",
"code": "SOCENGPRE",
"event_slug": "west_ham-tottenham-1401290",
"start": "1399117500",
"home_team": "West Ham",
"home_team_phid": null,
"home_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t523.png",
"home_team_short": "",
"away_team": "Tottenham",
"away_team_phid": null,
"away_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t498.png",
"away_team_short": "",
"phid": null
}, {
"id": "64711",
"code": "SOCENGPRE",
"event_slug": "manchester_u-sunderland-1401286",
"start": "1399125600",
"home_team": "Manchester U",
"home_team_phid": null,
"home_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t20790.png",
"home_team_short": "Man U",
"away_team": "Sunderland",
"away_team_phid": null,
"away_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t382.png",
"away_team_short": "",
"phid": null
}, {
"id": "64712",
"code": "SOCENGPRE",
"event_slug": "stoke-fulham-1401288",
"start": "1399125600",
"home_team": "Stoke",
"home_team_phid": null,
"home_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t389.png",
"home_team_short": "",
"away_team": "Fulham",
"away_team_phid": null,
"away_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t379.png",
"away_team_short": "",
"phid": null
}]
}
}
My goal is to just fetch the fixture id and the two teams competing. Any clue what I'm doing wrong?
Try using the below code , don't parse the JSON again as it is already handled, assuming string is your JSON object.
At beginning of script declare this variable result as array;
var result = [];
function getUpcomingFixtures() {
$.each( string , function ( i , val) {
$.each( val['fixtures'] , function ( k , fixturesData) {
result.push( { id: fixturesData.id ,
hometeam : fixturesData.home_team ,
awayteam : fixturesData.away_team
}
);
});
});
}
I am doing a youtube api call, and I get back a var result = JSON.stringify(response, '', 2); which looks like :
{
"kind": "youtube#searchListResponse",
"pageInfo": {
"totalResults": 1000000,
"resultsPerPage": 5
},
"items": [
{
"id": {
"kind": "youtube#video",
"videoId": "DEne4AoX_RU"
},
"kind": "youtube#searchResult",
"snippet": {
"publishedAt": "2012-11-22T22:36:15.000Z",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/DEne4AoX_RU/default.jpg"
},
"medium": {
"url": "https://i.ytimg.com/vi/DEne4AoX_RU/mqdefault.jpg"
},
"high": {
"url": "https://i.ytimg.com/vi/DEne4AoX_RU/hqdefault.jpg"
}
}
}
},
{
"id": {...}
The full object response returns correctly in my console but I want to retrieve thumbnails url and display it as an li-tagged html list
So I tried first to fetch in a list all the snippet entries :
var obj = $.parseJSON(result);
$.each(obj, function() {
output += this.snippet + + "<br/>";
});
console.log(output);
But I have an message in my console : Uncaught TypeError: Cannot read property 'length' of undefined. What am I missing ? Btw, I don't understand why there are still brackets in the json stringified result (if someone could advise some good doc to understand how to parse JSON, would be great:))
You should be looping over items:
$.each(obj.items, function() {
output += this.snippet ...
});
What you receive is JSON, you shouldn't stringify it.
Remove this line
var result = JSON.stringify(response, '', 2);
and simply do
var obj = $.parseJSON(response);
you want to iterate over items,
snippet is an object literal,
+ + is not valid javascript.