How to convert Google PageSpeed Insight JSON results to HTML - javascript

I have never worked with JSON before and I am stuck at converting my results to html. I would like them to spit out as ul's and li's preferably. I have tried plugins and Jquery scripts but nothing seems to work. My assumption is that the way I am spitting out the results is incorrect, but as I said I have no idea what I am doing with server response objects.
HTML:
<input type="text" placeholder="Enter webpage URL e.g.http://www.domain.com" id="url"/>
<input type="button" id="button" value="PageSpeed Data" onclick="clicked();" />
<div id="urlerror">Please Enter a Valid URL e.g. http://www.domain.com</div>
<pre id="data"></pre>
My code to get the results:
<script>
function clicked()
{
document.getElementById("urlerror").style.display = 'none';
var xhr = new XMLHttpRequest();
var url = document.getElementById("url").value;
if(url.indexOf('http://') === -1){document.getElementById("urlerror").style.display = 'block'; return;}
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url="+encodeURIComponent(url)+"&key=AIzaSyAIOUFcLYeo2WN1qbPSjlMbXmLi8kmOacw&strategy=mobile");
xhr.onload = function(){
document.getElementById("data").innerHTML = xhr.responseText;
}
xhr.send();
}
</script>
The resulting short snippet JSON object example (not full code):
{
"kind": "pagespeedonline#result",
"id": "http://www.celebritynewsdaily.us/",
"responseCode": 200,
"title": "Celebrity News Daily | Your Daily Source for Celebrity News & Updates",
"score": 64,
"pageStats": {
"numberResources": 71,
"numberHosts": 13,
"totalRequestBytes": "11777",
"numberStaticResources": 35,
"htmlResponseBytes": "235467",
"textResponseBytes": "238",
"cssResponseBytes": "135950",
"imageResponseBytes": "545748",
"javascriptResponseBytes": "762058",
"otherResponseBytes": "107518",
"numberJsResources": 13,
"numberCssResources": 11
},
"formattedResults": {
"locale": "en_US",
"ruleResults": {
"AvoidInterstitials": {
"localizedRuleName": "Avoid app install interstitials that hide content",
"ruleImpact": 0.0,
"urlBlocks": [
{
"header": {
"format": "Your page does not appear to have any app install interstitials that hide a significant amount of content. Learn more about the importance of avoiding the use of app install interstitials.",
"args": [
{
"type": "HYPERLINK",
"value": "https://developers.google.com/webmasters/mobile-sites/mobile-seo/common-mistakes/avoid-interstitials"
}
]
}
}
]
}
}
Any help getting this working is greatly appreciated.

Once you've got the JSON string, it is easy to convert into a JavaScript object by calling JSON.parse().
var myObject = JSON.parse(jsonString);
Once you've got the object, you can reference values within it as per a normal JS object; eg myObject.pageStats.numberResources, and use the DOM methods to insert them into DOM elements.

Related

Cannot render json file data to html

I have a JSON file named colors.js and looks like this:
{
"colors": [
{
"color": "black",
"category": "hue",
"type": "primary",
"code": {
"rgba": [255,255,255,1],
"hex": "#000"
}
},
{
"color": "white",
"category": "value",
"code": {
"rgba": [0,0,0,1],
"hex": "#FFF"
}
},
]
}
Here is how I have handled the html file:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script type="primary" src="colors.json"></script>
<script type="text/javascript">
colorItems=['beige', 'red', 'blue'];
function loadJSON() {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'colors.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
colorItems.push(JSON.parse(xobj.responseText)); // line 21
console.log(xobj.responseText); // line 22
}
};
}
function loadData(){
for (i=0; i<4; i++){
console.log(colorItems[i]);
document.getElementById('myP1').innerHTML+=colorItems[i]+'<br>';
}
}
</script>
<title></title>
</head>
<body onload="loadData()">
<p class="myP" id="myP1"></p>
<p class="myP" id="myP2"></p>
<p class="myP" id="myP3"></p>
<p class="myP" id="myP4"></p>
<p class="myP" id="myP5"></p>
</body>
</html>
I need when the page loads, information from each object (in the JSON file) be pushed to colorItems array. Then, they array renders to the paragraphs (that have class myP) in the body. However, I face two problems:
I am only able to get data to the paragraphs using getElementById, but
not getElementsByClassName .
I am not able to get the right data be pushed into colorItems array. Consequently, I am not able to get needed info on the html page.
This is how the output looks like (and how I need it to be):
You might want to take a look at this answer: Can I access variables from another file?
Firstly, you are not correctly receiving your .json because you are not even calling loadJSON(). Functions can be defined and called. What you did was just defining two functions and then calling the second one through the "onload" parameter. You forgot to call loadJSON(). In case you don't know how to do this, you have to write loadJSON() right inside loadData.
Seconly, even if you call that function, it won't work because you are not working on a server. Thus, as the question in the link above says, you'll get this error:
XMLHttpRequest cannot load file:///[path-to-file]. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
Regarding your first question, you should take a different approach. With a loop, you should create as many p elements as elements has the final colors array. Take a look at this guide: https://www.w3schools.com/js/js_htmldom_nodes.asp,
I think the way to push colors (object) to colorItems (array) could be this:
colorsjs.colors.map((o,i)=>{
colorItems.push(o.color);
});
Then, in load data:
function loadData(){
for (i=0; i<colorItems.length; i++){
document.getElementById('myP'+(i+1)).innerHTML = colorItems[i]+'<br>';
}
}
Full example here https://jsfiddle.net/or9o9upb/
If you want to iterate over the class element:
var el = document.getElementsByClassName("myP");
for(let i = 0; i<el.length; i++){
el[i].innerHTML = colorItems[i];
}
Example here https://jsfiddle.net/8Lq2nd23/
If you have a js file with the json:
<script src="/path/to/colors.js"></script>
<script>
//it's already available
console.log(colorsjs);
</script>
But your js have to be something like this:
var colorsjs = {
"colors": [//....code

Error during serialization or deserialization using the JSON JavaScriptSerializer_Unable to fix using previous answers

I know this is a duplicate question but I tried all the previous answers. Not working for me. So I give here my code. When try to load more than 2000 record I got this error.
"Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set
on the maxJsonLength property."
In Controller
public ActionResult Index(SearchFilter sf)
{
Model m = new Model();
IList<Info> Details;
IList<rViewModel> RLst = new List<rViewModel>();
using (var db = new con())
{
RLst = (from p in Details
select new rViewModel
{
Id=p.Id,
Description = p.Description,
Remark = p.Remark,
}).ToList();
m.Result = RLst;
}
return View(m);
}
In View,
$(document).ready(function () {
$('#Product').dataTable({
"columnDefs": [
{ "width": "20%", "targets": 0, "orderable": true, },
{ "width": "40%", "targets": 1,"orderable": true, },
{ "width": "40%", "targets": 2,"orderable": true, },
],"oLanguage": {"sSearch": "Filter:"}
});
var t = $('#Product').DataTable();
t.clear();t.draw();
var model =#Html.Raw(Json.Encode(Model.Result));
if(model!=null && model.length>0 )
{
AddData(model);
}
$('#Id').focus();
});
Result Model is actually a partial view.
On the line in view,
var model =#Html.Raw(Json.Encode(Model.Result));
I got this error. Error image attached below
How to fix?
I tried adding
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483644"/>
</webServices>
</scripting>
</system.web.extensions>
in web.config already its not working.stuck in this for more than 2 days.. Kindly help..
Thank you mr.Tetsuya Yamamoto for your reference. So far I tried all the link. But as per your link I tried the coding below.
In view
#{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
var jsonModel = serializer.Serialize(Model.Result);
}
and at the line where I got error,I changed my one
var model =#Html.Raw(Json.Encode(Model.Result));
into the line as below:
var model =#Html.Raw(jsonModel);
Previously also I tried these coding, but wrongly entered in controller. From your link only I find out need to put in view. This will help some one whose web.config declaration is not working.
Link Courtesy(once again) as follows: Json Encode throwing exception json length exceeded
"jsonSerialization maxJsonLength" did not work for me on this problem
But I reference #Halim answer.
This also works for me:
previous code with the problem:
<script>
$(document).ready(function () {
modelname(#Html.Raw(Json.Encode(Model)));
});
</script>
code resolution:
<script>
$(document).ready(function () {
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
var jsonModel = serializer.Serialize(Model);
modelname(jsonModel)
});
</script>

Google Charts with different Json files

With all the different ways to write a Json file, I wanted to learn more about how to write them and how to use them in a Google Chart.
First I started with making and using the following Json:
[
{
"Voetballer" : "Christiano Ronaldo",
"Jaar_2010" : 79000000.00,
"Jaar_2011" : 79700000.00,
"Jaar_2012" : 80000000.00,
"Jaar_2013" : 79500000.00,
"Jaar_2014" : 80000000.00,
"Jaar_2015" : 81000000.00
},
{
"Voetballer" : "Lionel Messi",
"Jaar_2010" : 55500000.00,
"Jaar_2011" : 60000000.00,
"Jaar_2012" : 61500000.00,
"Jaar_2013" : 62000000.00,
"Jaar_2014" : 63000000.00,
"Jaar_2015" : 64700000.00
}
(just a part of the Json)
And I made a chart with the help of Google's chart API and the following code:
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart()
{
$.getJSON('voetbal.json', function(data)
{
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('string', 'jaar');
$.each(data, function(key, value)
{
dataTable.addColumn('number', value.Voetballer);
});
count=0;
$.each(data[0], function(key, value)
{
if (key != "Voetballer")
{
dataTable.addRows(1);
var Year = key.split("_");
dataTable.setValue(count, 0, Year[1]);
count++;
}
});
count=1;
$.each(data, function(i, object)
{
teller=0;
$.each(data[i], function(key, value)
{
if (key != "Voetballer")
{
dataTable.setValue(teller, count, value);
teller++;
}
});
count++;
});
var options =
{
colors : ['#8bbe24','#344d59','#d1ceb2','#c95338','#fcc800','#00a0e9','#601986','#e4ebe5'],
title : " Top earnings ",
seriesType: 'bars',
legend: {position: 'right'},
series: {11: {type: 'line'}}
};
var chart = new google.visualization.ComboChart(document.getElementById('visualization'));
chart.draw(dataTable, options);
});
}
</script>
</head>
<body>
<div id="visualization"></div>
</body>
This chart works great!
So I wanted to move on to a different Json file, create a correct file at first which became this one:
[
{
"round1": [
{
"playerA": 62,
"playerB": 98,
"playerC": 97,
"playerD": 94,
"playerE": 96
}
]
},
{
"round2": [
{
"playerA": 77,
"playerB": 40,
"playerC": 41,
"playerD": 99,
"playerE": 76
}
]
}
(it goes on until round 10)
How ever I can't get this Json file to work using the code from my previous chart so I changed the Json a bit to this:
[
{
"round": 1 [
{
"playerA": 62,
"playerB": 98,
"playerC": 97,
"playerD": 94,
"playerE": 96
}
]
},
In hope that it would make it easier but all I seem to manage is a empty screen, without errors.
Hopefully there's someone out there that can either point me in the right direction or show me what I'm doing wrong, my knowledge is very slim about Json files in general. I just figured I could use the working previous code and mainly change some names and be able to use pretty much the same code.
So my question in short: How can I use the second Json file I made with Google charts? And is it easier to use the code I've already once made, or go from scratch because of the different Json file? And if so, please tell me how/point me in the right way. All this Json stuff is confusing =)
The issue is that you changed the data structure of the JSON file. The first JSON file was an Array of objects [{obj1}, {obj2}...] and the second JSON file is an ARRAY of objects that have a key with an array as a value [{obj1:[array1]},{obj2:[array2]}...]. Both are completely valid JSON formats, but the API can only render the data under the first format. Please see this documentation to understand how you should be preparing the data for a google chart.
https://developers.google.com/chart/interactive/docs/basic_preparing_data

Get Wikipedia pageid from title

I'm trying to get an image from a Wikipedia article. I have the title of the article but it seems like I need to know the pageid to access the thumbnail. How do I get the pageid from the title?
My JavaScript code:
$.getJSON("http://en.wikipedia.org/w/api.php?action=query&titles=" + article + "&prop=pageimages&format=json&pithumbsize=350", function (data) {
imageURL = data.query.pages[/* pageid */].thumbnail.source;
});
Here's what I'm parsing (example for article = "Car"):
{"query":{"pages":{"13673345":{"pageid":13673345,"ns":0,"title":"Car","thumbnail":{"source":"http://upload.wikimedia.org/wikipedia/commons/thumb/1/1e/Benz-velo.jpg/100px-Benz-velo.jpg","width":100,"height":80},"pageimage":"Benz-velo.jpg"}}}}
^ It seems like I first need to know that it's the 13673345 index.
OP asks how to "access the thumbnail", i.e., the URL within the returned data. He did not ask how to access the full image behind the thumbnail ... which is something other answers address.
OP's problem is that the data is keyed to the page ID. In fact, the query could return more than one article in which case there would be multiple page IDs and thumbnails.
The following query returns the data used in the code snippet:
http://en.wikipedia.org/w/api.php?action=query&titles=Stack_Overflow&prop=pageimages&format=json&pithumbsize=350
And OP can extract the page IDs using this code:
var pageid = [];
for( var id in data.query.pages ) {
pageid.push( id );
}
Run the code snippet below to test.
<html>
<body>
<img id="thumbnail"/>
<script type="text/javascript">
var data = {
"query":
{
"normalized": [
{
"from": "Stack_Overflow",
"to": "Stack Overflow"
}],
"pages":
{
"21721040":
{
"pageid": 21721040,
"ns": 0,
"title": "Stack Overflow",
"thumbnail":
{
"source": "http://upload.wikimedia.org/wikipedia/commons/thumb/6/6a/Stack_Overflow_homepage.png/350px-Stack_Overflow_homepage.png",
"width": 350,
"height": 185
},
"pageimage": "Stack_Overflow_homepage.png"
}
}
}
};
// get the page IDs
var pageid = [];
for( var id in data.query.pages ) {
pageid.push( id );
}
// display the thumbnail using a page ID
document.getElementById('thumbnail').src = data.query.pages[ pageid[0] ].thumbnail.source;
</script>
</body>
</html>
Just build your JSON object with JSON.parse so you have an object that looks like:
var response = {
query: {
pages: {
"13673345":{
pageid: 13673345,
ns: 0,
title: "Car",
thumbnail: {
source: "http://upload.wikimedia.org/wikipedia/commons/thumb/1/1e/Benz-velo.jpg/100px-Benz-velo.jpg",
width: 100,
height: 80
},
pageimage: "Benz-velo.jpg"
}
}
}
};
And then you can clearly see you don't need pageid in the slightest, you just need to process the correct "pages" object.
In this case there's only one, but even if there would be multiple, just run through Object.keys for the response.query.pages object:
var pages = response.query.pages;
var propertyNames = Object.keys(pages);
propertyNames.forEach(function(propertyName) {
var page = pages[propertyName];
var thumbnail = page.thumbnail.src;
var imgURL = thumbnail.replace("/thumb/",'').replace(/\.(jpg|png).*/,".$1");
doSomethingWith(imgURL);
});
(note the file extension regexp, which we do because who says all images are jpg? Better to pick jpg and png, since those are the two prevailing image formats on the web)

Calling JSON file from URL in JavaScript

I am trying to read a JSON file from a webpage and display the route contained in the file over my map in OpenLayers. I found another example similar to mine, How to fetch JSON from a URL using JavaScript?, but I couldn't get it working.
I create the URL string containing as, for example, something like this:
http://router.project-osrm.org/viaroute?rebuild=1&loc=43.46711564169348,-3.880102031707764&loc=43.4669443349282,-3.862788677215576&output=json
This webpage should return a JSON file with all the points I have to follow to reach my end point. I know this works because I tried with this example:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Open Space Web-Map builder Code</title>
</head>
<body>
<div class="header-content">
[
<a class="result-link" onClick="document.location.href='http://router.project- osrm.org/viaroute? rebuild=1&loc=43.46711564169348,-3.880102031707764&loc=43.4669443349282,-3.862788677215576&output=json';">Generar ruta</a>
]
</div>
</body>
</html>​
And it returns a JSON file, as shown below. But if I try to use my page, it doesn't work. I have this function to read JSON file:
function pintarRutaCamion() {
capaRuta = new OpenLayers.Layer.Vector("capaRuta");
var style_green = {
strokeColor: "#00FF00",
strokeOpacity: 1,
strokeWidth: 6
};
var pointRuta = [];
alert(rutaCompleta); //show the complete url
JQ.getJSON(rutaCompleta, function(puntosRuta) {
alert(puntosRuta.route_geometry.length); //show size of returned json file
for (i = 0; i < puntosRuta.route_geometry.length; i++) {
coordenadas = new OpenLayers.LonLat(puntosRuta.route_geometry[i][1], puntosRuta.route_geometry[i][0]).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
pointruta.push(coordenadas);
}
});
//create a polyline feature from the array of points
var lineString = new OpenLayers.Geometry.LineString(pointRuta);
var lineFeature = new OpenLayers.Feature.Vector(lineString, null, style_green);
capaRuta.addFeatures([lineFeature]);
//add it to the map
map.addLayer(capaRuta);
}​
The JSON file should be something like this:
{"version": 0.3,
"status": 0,
"status_message": "Found route between points",
"route_geometry": [[43.46716, -3.87987],[43.46668, -3.87963],[43.46706, -3.87761],[43.46593, -3.87740],[43.46571, -3.87552],[43.46559, -3.87515],[43.46553, -3.87512],[43.46549, -3.87504],[43.46548, -3.87496],[43.46550, -3.87487],[43.46554, -3.87482],[43.46558, -3.87433],[43.46533, -3.87210],[43.46535, -3.87185],[43.46546, -3.87128],[43.46592, -3.86911],[43.46598, -3.86859],[43.46593, -3.86824],[43.46589, -3.86818],[43.46587, -3.86808],[43.46588, -3.86800],[43.46581, -3.86780],[43.46560, -3.86761],[43.46545, -3.86756],[43.46526, -3.86756],[43.46517, -3.86760],[43.46511, -3.86760],[43.46502, -3.86753],[43.46498, -3.86743],[43.46497, -3.86734],[43.46499, -3.86718],[43.46510, -3.86711],[43.46521, -3.86696],[43.46530, -3.86675],[43.46547, -3.86606],[43.46569, -3.86504],[43.46639, -3.86166],[43.46716, -3.86194],[43.46698, -3.86278]],
"route_instructions": [["10","",56,0,155,"56m","SE",203.5],["7","",167,1,242,"167m","E",281.06],["3","Calle Polvorín",126,2,182,"126m","S",189.18],["7","CA-231",185,3,131,"185m","E",262.42],["11-2","CA-231",536,10,350,"536m","E",277.7],["11-1","CA-231",82,20,52,"82m","E",250.51],["11-2","Calle del Somo",36,31,19,"36m","NE",310.15],["1","Calle de El Somo",426,33,236,"426m","E",285.81],["7","Calle de Antonio Nebrija",88,36,127,"88m","N",17.56],["7","Calle de Manuel Cacicedo",70,37,76,"70m","W",103.84],["15","",0,38,0,"","N",0.0]],
"route_summary": {"total_distance": 1890,
"total_time": 179,
"start_point": "",
"end_point": "Calle de Manuel Cacicedo"},
"via_points": [],
"hint_data": {"checksum": -1013584035,
"locations": ["xqyjHgAAAACbAAAAzwAAABj5Tb5MZ9s_XFNCAG0U-v9", "WVr_FtzAKgAzAQAAaAAAAK5H_5Np-ec_SlNCABob-v9"]},
"transactionId": "OSRM Routing Engine JSON Descriptor (v0.3)"}
But it is impossible to get inside that function. I don't know what happens. I tried writing document.location.href= as the other example in the URL string but this also fails. Can anyone suggest why this is not working?
Your url should be like this,
http://router.project-osrm.org/viaroute?rebuild=1&loc=43.46711564169348,-3.880102031707764&loc=43.4669443349282,-3.862788677215576&output=json
And It seems that doesn't suppport jsonp callback, so you cannot request with $.getJSON directly because of Cross-Origin Resource Sharing.
you should use a proxy to avoid this problem, for example you can use YQL
here is an example with your url

Categories

Resources