-1

I am unable to parse the json file obtained from this http://dbpedia.org/data/Los_Angeles.json url.

I need to find the populationTotal, areaTotal, populationDensity fields from the json data obatined from the URL above.

This is a snippet of the json data obtained from http://dbpedia.org/data/Los_Angeles.json url. Eg.

"http://dbpedia.org/ontology/populationTotal" : [ 
{ "type" : "literal",
  "value" : 3792621 , 
  "datatype" : "http://www.w3.org/2001/XMLSchema#integer" } ] ,
"http://dbpedia.org/ontology/PopulatedPlace/areaTotal" : [ 
{ "type" : "literal", 
  "value" : "1301.9688931491348" , 
  "datatype" : "http://dbpedia.org/datatype/squareKilometre" } ,

How could i get this Json data and output it using Javascript.

2 Answers2

0

Do this help you?

var populationTotalData=[];
for(var key in data) {
    if(key.match(/populationTotal/))
    // or simplier: if(key.indexOf("populationTotal")>-1)
        populationTotalData.push(data[key]);
}
PhuLuong
  • 527
  • 4
  • 11
0

Because of the Same-Origin Policy, you often can't directly fetch the data using JavaScript. However, it turns out that dbpedia.org supports JSON-P, so you can get the data with straight JavaScript like this:

// This is the "callback" function. The 'data' variable will contain the JSON.
// You can access it like I have done in the alert below.
mycallback = function(data){
    alert(data["http://fr.dbpedia.org/resource/Los_Angeles"]["http://www.w3.org/2002/07/owl#sameAs"][0].value);
};

// This is the function we use to fetch the JSON data:
function requestServerCall(url) {
    var head = document.head;
    var script = document.createElement("script");

    script.setAttribute("src", url);
    head.appendChild(script);
    head.removeChild(script);
}

// Note the query string that I have added (?callback=mycallback).
// This is the name of the function that will be called with the JSON data.
requestServerCall('http://dbpedia.org/data/Los_Angeles.json?callback=mycallback');

A lot more really excellent information on JSONP can be found here. You could loop inside of the mycallback function using some code like this. Obviously, you'd have to make nested loops to get exactly what you want, so this code would need modifying to fit your exact needs.

<script type="text/javascript">
  for(var index in data) { 
    console.log(data[index]); 
  }
</script>

The other method would be via PHP. For example: you could pitch the whole page into a JavaScript variable like this:

<?php
  $los_angeles = file_get_contents('http://dbpedia.org/data/Los_Angeles.json');
?>
<script type="text/javascript">
  var data = <?php echo $los_angeles; ?>;
  alert(data["http://fr.dbpedia.org/resource/Los_Angeles"]["http://www.w3.org/2002/07/owl#sameAs"][0].value)
</script>
Community
  • 1
  • 1
Jonathan
  • 6,507
  • 5
  • 37
  • 47