Calling JSON file from URL in JavaScript - 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

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

How to convert Google PageSpeed Insight JSON results to HTML

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.

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)

How to display a list of JSON objects onto html page

NOTE: Need to implement this without the use of jQuery or any other open source code.
Here is what I have
HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Model</title>
<script src="js.js"></script>
</head>
<body>
<h1>Browse all our products below:</h1>
Name: <span id="name"></span><br>
Desc: <span id="desc"></span><br>
Cost: <span id="cost"></span><br>
Stock: <span id="stock"></span>
</body>
</html>
js.js is below
var getProducts = function(){
console.log("Getting Products...");
var success = function() {
var product = JSON.parse(xhr.responseText);
console.log(product);
document.getElementById("name").innerHTML = product.name;
document.getElementById("desc").innerHTML = product.desc;
document.getElementById("cost").innerHTML = product.cost;
document.getElementById("stock").innerHTML = product.stock;
}
};
xhr = new XMLHttpRequest();
xhr.open("GET", "back.php");
xhr.addEventListener("load", success);
xhr.send();
};
window.addEventListener("load", getProducts);
back.php returns the following from a database. They have been json_encoded:
{"name":"TESTPRODUCT","desc":"TESTIN12356879CEWBLABHDSB","cost":"123.45","stock":"6"}
{"name":"soot","desc":"soooottty black","cost":"980.00","stock":"10"}
{"name":"baby","desc":"chucky doll","cost":"7.92","stock":"34"}
{"name":"bob","desc":"fydrtsfxgcvnb","cost":"3546.00","stock":"978"}
{"name":"bolly","desc":"ball","cost":"77.00","stock":"89"}
I need to display these objects onto the html page. I know I need to implement a for loop however, no matter whatever I try, a parse error for JSON comes up.
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at
line 1 column 86 of the JSON data
var product = JSON.parse(xhr.responseText);
Would much appreciate it if someone could help me understand how to display all the JSON objects onto the html page.
Your JSON is invalid. You need to put the objects in an array, and separate them by commas.
[{"name":"TESTPRODUCT","desc":"TESTIN12356879CEWBLABHDSB","cost":"123.45","stock":"6"},
{"name":"soot","desc":"soooottty black","cost":"980.00","stock":"10"},
{"name":"baby","desc":"chucky doll","cost":"7.92","stock":"34"},
{"name":"bob","desc":"fydrtsfxgcvnb","cost":"3546.00","stock":"978"},
{"name":"bolly","desc":"ball","cost":"77.00","stock":"89"}]
Here is an example using open source project jinqJs
Also the example is using jQuery.
Fiddle Example
//data can also be a string to a url that returns JSON
jinqJs().from(data).select(function(row) {
$('#items')
.append($("<option></option>")
.attr("value",row.nam)
.text(row.desc));
}
);

Reading a Javascript object from UIWebview

I have a webpage which has data within a javascript object in it. I would like to get access to this data from the UIWebView to use within the native ObjectiveC code.
I have tried a number of ways
In the delegate method -(void) webViewDidFinishLoad:(UIWebView *) webView
I tried accessing the object using
[myWebView stringByEvaluatingJavaScriptFromString:#""];
but there didnt seem an easy way to pull in the structured data
Other option I thought was to
just load the HTML as a string and parse it but this seemed like a really ugly approach.
An example of the HTML I have is.
<html>
<head>
<script type="text/javascript">
$(function() {
myData[0] = {
name: 'data title',
data: [
[1281880800000, 4],[1282485600000, 12],[1283090400000, 15],[1283695200000, 107],[1284300000000, 11],[1284904800000, 14],[1285509600000, 3],[1286110800000, 10],[1286715600000, 12],[1287320400000, 2],[1287925200000, 304],[1288530000000, 18],[1289134800000, 22],[1289739600000, 5],[1290344400000, 6],[1290949200000, 14],[1291554000000, 6],[1292158800000, 10],[1292763600000, 9],[1293368400000, 0],[1293973200000, 4],[1294578000000, 2],[1295182800000, 17],[1295787600000, 6],[1296392400000, 4],[1296997200000, 7],[1297602000000, 50],[1298206800000, 2],[1298811600000, 3],[1299416400000, 3],[1300021200000, 301],[1300626000000, 1],[1301230800000, 72],[1301839200000, 6],[1302444000000, 5],[1303048800000, 2],[1303653600000, 5],[1304258400000, 7],[1304863200000, 8],[1305468000000, 34],[1306072800000, 12],[1306677600000, 6],[1307282400000, 2],[1307887200000, 2],[1308492000000, 7],[1309096800000, 30],[1309701600000, 63],[1310306400000, 3],[1310911200000, 9],[1311516000000, 3],[1312120800000, 4] ],
color: '#ff1430'
};
myData[1] = {
name: 'Other Data',
data: [
[1281880800000, 29],[1282485600000, 402],[1283090400000, 0],[1283695200000, 1],[1284300000000, 1],[1284904800000, 0],[1285509600000, 0],[1286110800000, 0],[1286715600000, 1],[1287320400000, 10],[1287925200000, 2],[1288530000000, 0],[1289134800000, 10],[1289739600000, 1],[1290344400000, 3],[1290949200000, 26],[1291554000000, 2],[1292158800000, 5],[1292763600000, 3],[1293368400000, 1],[1293973200000, 3],[1294578000000, 26],[1295182800000, 2],[1295787600000, 0],[1296392400000, 5],[1296997200000, 47],[1297602000000, 36],[1298206800000, 12],[1298811600000, 21],[1299416400000, 0],[1300021200000, 0],[1300626000000, 16],[1301230800000, 0],[1301839200000, 3],[1302444000000, 4],[1303048800000, 2],[1303653600000, 0],[1304258400000, 1],[1304863200000, 5],[1305468000000, 2],[1306072800000, 1],[1306677600000, 4],[1307282400000, 1],[1307887200000, 1],[1308492000000, 51],[1309096800000, 77],[1309701600000, 3],[1310306400000, 2],[1310911200000, 1],[1311516000000, 10],[1312120800000, 4] ],
color: '#007396'
};
</script>
</head>
<body>
</body>
</html>
EDIT:
To clarify I would like to be able to get access to the myData structure in the above HTML example within objective C as a NSDictionary or similar.
NSInteger x = [[[[[myDataArray objectAtIndex:0] objectForKey:#"data"] objectAtIndex:0] objectAtIndex:0]
I have used http://stig.github.com/json-framework for converting JSON into NSDictionary but was wondering how I could combine this to access this javascript object from within the HTML
I think this is a duplicate post. But still let me clarify your doubt -
[webView stringByEvaluatingJavaScriptFromString:#"obj.func();"];
EDIT: Check this - How to inject Javascript in UIWebView
Hope this helps...

Categories

Resources