Parsing this JSON data with JavaScript - javascript

We have a working PHP function that grabs specific YouTube video information using YouTube API v3.
We're trying to use JavaScript (jQuery) to do the same thing. The issue is that using our PHP function causes the page to load very slowly while it's retrieving the data. We're hoping that using JavaScript will allow our page to load before (or during) the data requests from YouTube.
First of all, this is an example url for one of our videos (you will need an API key to see the returned information yourself):
https://www.googleapis.com/youtube/v3/videos?part=statistics&id=ce5KbCTfHoA&key={YOUR_API_KEY}
That specific url will return this information:
{
"kind": "youtube#videoListResponse",
"etag": "\"jOXstHOM20qemPbHbyzf7ztZ7rI/qRFx1vTFF-k7dkRzNB5rGQ-dqiQ\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#video",
"etag": "\"jOXstHOM20qemPbHbyzf7ztZ7rI/2yn7rCfXCu0o-GNVtMEQqYssSpE\"",
"id": "ce5KbCTfHoA",
"statistics": {
"viewCount": "33169",
"likeCount": "281",
"dislikeCount": "3",
"favoriteCount": "0",
"commentCount": "85"
}
}
]
}
We are trying to retrieve the likeCount and dislikeCount of this video using JavaScript.
We can achieve this using PHP in the following manner:
function getVideoRatings() {
$JSON = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=statistics&id={VIDEO_ID}&key={YOUR_API_KEY}");
$json_data = json_decode($JSON, true);
$likes = $json_data['items'][0]['statistics']['likeCount'];
$dislikes = $json_data['items'][0]['statistics']['dislikeCount'];
/* some other code... */
}
This successfully parses the json information returned by google and returns the likes (likeCount) and dislikes (dislikeCount) for the video.
We'd like to do this using JavaScript (jQuery). Can anyone please help me figure this out?
I really appreciate any help or bump in the right direction.
Thanks

$.getJSON("https://www.googleapis.com/youtube/v3/videos?part=statistics&id=ce5KbCTfHoA&key={YOUR_API_KEY}", function( data ) {
var likes = data['items'][0]['statistics']['likeCount'];
});
This should work. Use jQuery documentation.

Related

What paramater am I missing for YouTube Data API Insert method

I'm using Google's Apps Script for this project. I'm using the YouTube data API V3 and of that API I am using the PlaylistItems class. I'm trying to insert a video into a playlist and I've pieced together what I can from the documentation that they have given.
YouTube.PlaylistItems.insert({
"part": [
"snippet"
],
"resource": {
"snippet": {
"playlistId": "PL5t3YGq3D2WnrLyuYL9WCgprQ2RUcwl8a",
"position": 0,
"resourceId": {
"kind": "youtube#video",
"videoId": testVidId
// testVidId is the ID of the video I'm trying to insert
}
}
}
});
When I run this though, I get an error of
Exception: Invalid number of arguments provided. Expected 2-3 only
My question is: what argument am I missing?
I believe your goal as follows.
You want to insert an item to the play list using Google Apps Script.
Modification point:
When YouTube.PlaylistItems.insert(resource, part) is used, the arguments are resource, part which are an object and an array of string, respectively.
When your script is modified, it becomes as follows.
Modified script:
YouTube.PlaylistItems.insert(
{
"snippet": {
"playlistId": "PL5t3YGq3D2WnrLyuYL9WCgprQ2RUcwl8a",
"position": 0,
"resourceId": {
"kind": "youtube#video",
"videoId": testVidId
}
}
},
["snippet"]
);
Note:
Before you use this, please confirm whether YouTube Data API v3 is enabled at Advanced Google services, again.
Reference:
PlaylistItems: insert

Use the YouTube API to check if a video is embeddable

I'm trying to figure out if a YouTube video is embeddable using the YouTube Data API v3, from answers to similar questions I noticed the status.embeddable property of videos, for a request like this:
https://www.googleapis.com/youtube/v3/videos?id=63flkf3S1bE&part=contentDetails,status&key={MY_API_KEY}
The response is the following
{
"kind": "youtube#videoListResponse",
"etag": "\"ksCrgYQhtFrXgbHAhi9Fo5t0C2I/ctZQYtBcOuMdnQXh8-Fv1EbS_VA\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#video",
"etag": "\"ksCrgYQhtFrXgbHAhi9Fo5t0C2I/Cd8aGZD09NPuGYNumIEozZs2S90\"",
"id": "63flkf3S1bE",
"contentDetails": {
"duration": "PT8M23S",
"dimension": "2d",
"definition": "hd",
"caption": "false",
"licensedContent": false,
"projection": "rectangular"
},
"status": {
"uploadStatus": "processed",
"privacyStatus": "public",
"license": "youtube",
"embeddable": true,
"publicStatsViewable": true,
"madeForKids": false
}
}
]
}
The embeddable parameter under status is returned as true, HOWEVER this video is not actually embeddable, as can be seen here.
When actually embedding the video using the iframe API, there is a more detailed error message as well:
Video unavailable
This video contains content from International Olympic Committee, who has blocked it from display on this website or application.
Watch on YouTube
I don't see how it is possible to detect this case from the YouTube Data API - can anyone help out?
Other option is used in this answer:
Here, you can use the following URL:
https://www.youtube.com/get_video_info?video_id=<VIDEO_ID>
Where VIDEO_ID is the YouTube video_id you want retrieve the information.
In this case, once you get the response, you'll see a property called "playabilityStatus.status".
Here is a extract of the response:
"playabilityStatus": {
"status": "UNPLAYABLE",
"reason": "The video is not available",
"errorScreen": {
"playerErrorMessageRenderer": {
"reason": {
"simpleText": "The video is not available"
},
Additional to johnh10's answer, some of the results saw in the YouTube webpage is not always shown/available in the APIs.
I have the answer. The file that outputs from the https://www.youtube.com/get_video_info?video_id=
is nothing more than a standard text file that is URLENCODED.
To see it properly you first have to DECODE it using a URLDECODER and then you have to separate the json part from the URL querystring part. To take a look at the JSON part you can use a json formatted and to look at the URL part you can use PrettyPrint URL.
Once you do this you will notice that the tag you are looking for to validate weather the video is playable or not is the one mentioned by the other user here. It sits on the URL parameter named "player_response", after you DECODE the file you will find it easily. This parameter holds a longer JSON file that has the playability status under playabilityStatus.Status.
To manipulate it on Javascript simply parse this part of the file as a JSON file and access your node of choice, or parse it as a text and search for the playabilityStatus node that must be unencoded if you dont care to decode it (nothing to fear, only some %2D and %7B instead of spaces and curly brackets).
Good luck!
Unfortunately, this 'copyright check' happens directly from the player. This data is not available through the API.

result not coming with d3js?

After lot of help from stackoverflow folks,finally resolved my json and now its looking good.
luck.json--->
{
"PERFECT_JSON_object":
{
"51b59c1bbae1c":
[
{ "id": "parties", "float_1": "0.006" , "float_2": "0.9"},
{ "id": "royal-challenge", "float_1": "0.02" , "float_2": "0.333" },
{ "id": "star-speak","float_1": "0.02","float_2":"0.1" }
],
"51b59c1bbae3c":
[
{ "id": "parties","float_1": "0.006" , "float_2": "0.9"},
{ "id": "star-speak","float_1": "0.02", "float_2": "0.009" }
],
"51b59c1bbae5c":
[
{ "id": "parties","float_1": "0.006" , "float_2": "0.9"}
]
}
}
I have been trying to get my head around d3js with json,and I must say I have progressed quite a bit.But I am still not able to get the output with json data.
I went through these link`s but dint help.
https://github.com/mbostock/d3/wiki/Requests
d3.js & json - simple sample code?
Access / process (nested) objects, arrays or JSON
MyFIDDLE with json(no output,something wrong in here)
same fiddle with some static values( without Json)--
This is the result that I want.
I know that d3.json method requires json file to be on server.For temporary basis,as the json file is small can we include it directly in a variable in our d3 script??
I think I am messing up with json data in a wrong way.Can somebody help me with it
Yes, you can just add the JSON in a variable and run it this way. See here for the updated jsfiddle. You basically just add your JSON after var data =.

How to translate Solr JSON response into HTML while JSON is different every time

I am using Solr 4 for searching in a java web application.Solr produces a JSON response from which i have to extract search results and translate them into html so user can read that.
I know one solution but it seems dumb an I think there must be intelligent ideas.
{
"responseHeader": {
"status": 0,
"QTime": 0,
"params": {
"fl": "id,title",
"indent": "true",
"q": "solr",
"wt": "json"
}
},
"response": {
"numFound": 3,
"start": 0,
"docs": [
{
"id": "1",
"title": "Solr cookbook"
},
{
"id": "2",
"title": "Solr results"
},
{
"id": "3",
"title": "Solr perfect search"
}
]
}
}
After that i eval this text as:
var obj = eval ("(" + txt + ")");
To generate html page i can use either
<script>
document.getElementById("id").innerHTML = obj.response.docs[1].id
document.getElementById("title").innerHTML = obj.response.docs[1].title
</script>
or
document.write(obj.response.docs[1].id);
But limitation is that every time solr gives response with different object structure i.e. an object may have age feild but other can not have because it depends on query.
I want to use a sigle JSP page to display search results(like Google)
for all search queries
is it possible to write a single code segment which works for any possible search results with different schema.
Javascript stops working after encountering any error which is likely in my case. that's also problem.if I use for loop to traverse the object hierarchy it is highly error -prone.
Is it possible with a single view page Thanks.
You might want to consider using ajax-solr - A JavaScript framework for creating user interfaces to Solr
I suggest using Velocity templating which is readily supported in Solr - instead of extracting data from the JSON and rendering the HTML via JS.
Docs here

Parse JSON from local url with JQuery

I have a local url where i can retrieve a json file. I also have a simple website which is build using JQuery.
I've looked up many sites for tutorials and sample code on how to retrieve the json input and parse it so i can display it on my site. However non were helpful as i still can't make it work.
So as a last resort i'm going to ask stackoverflow for your help. I have a lot of java knowledge, but I'm relative new to 'web'-development and know some basics of javascript.
This is a sample output of my url:
[
{
"baken": "not implemented...",
"deviceType": "Optimus 2X",
"batteryLevel": "1.0",
"gps": {
"speed": 0,
"Date": "TueNov0100: 34: 49CET2011",
"Accuracy": 35,
"longitude": {removed},
"latitude": {removed},
"Provider": "gps"
},
"deviceId": "4423"
},
{
"baken": "notimplemented...",
"deviceType": "iPhone",
"batteryLevel": "30.0",
"gps": {
"speed": 0,
"Date": "TueNov0116: 18: 51CET2011",
"Accuracy": 65,
"longitude": {removed},
"latitude": {removed},
"Provider": null
},
"deviceId": "4426"
}
]
Hope you can help me..
If you are running a local web-server and the website and the json file are served by it you can simply do:
$.getJSON('path/to/json/file.json', function(data) {
document.write(data);
})
If you are just using files and no webserver you might get a problem with the origin-policy of the browser since AJAX request cannot be send via cross-domain and the origin domain is 'null' per default for request from local files.
If you are using Chrome you can try the --allow-file-access-from-files parameter for developing purposes.
Your URL returns invalid json. Try pasting it in jsonlint.com and validating it there and you'll see what I mean. Even the code highlighting here on stackoverflow is showing you what's wrong. :)
Edit: To parse it you can use jQuery.parseJSON
jQuery.parseJSON('{"foo": "goo"}');
$.get('/some.json', function(data) {
// data[0]["baken"] == "not implemented..."
});
See http://api.jquery.com/jQuery.get/
You don't need to parse the json -- that is why people like it. It becomes a native JavaScript object.
For your example if you put the results in a variable called data then you could do things like this:
data[0].deviceType // would be "Optimus 2x"
data[0].gps.speed // would be numeric 0
etc.
The most natural way is to allow jQuery to make an AJAX call for you once you've already entered the page. Here's an example:
$.ready(function() {
// put your other code for page initialization here
// set up a global object, for namespacing issues, to hold your JSON.
// this allows your to be a good "web" citizen, because you will create
// one object in the global space that will house your objects without
// clobbering other global objects from other scripts, e.g., jQuery
// makes the global objects '$' and 'jQuery'
myObjects = {};
// start JSON retrieval here
$.getJSON('/path/to/json/file.json', function(data) {
// 'data' contains your JSON.
// do things with it here in the context of this function.
// then add it to your global object for later use.
myObjects.myJson = data;
});
});
The API documentation is here

Categories

Resources