How to use JSON to retrieve dbpedia json data - javascript

In my php code, I am retrieving json data as below.
<?php
$url = "http://dbpedia.org/data/Los_Angeles.json";
$data = file_get_contents($url);
echo $data;
?>
The javascript code consumes this json data returned from php and gets the json object as below.
var doc = eval('(' + request.responseText + ')');
How to retrieve the following json data using dot notations where the keys contain URLs.
My guess is to use encoding. Please guide along these lines
"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" }

Related

About Parse API Data

The API returns data like this:
data({"total" : 100, "totalPage" : 10, "page" : 2, "items" : ["data"]})
How to parse this? For example, I want to get totalPage, How to do this? Use PHP or JavaScript.
Try using PHP
$str = <<<JSON
{"total" : 100, "totalPage" : 10, "page" : 2, "items" : ["data"]}
JSON;
$json = json_decode($str);
echo $json->totalPage;
I found that it's a jsonp data~~

json string is not converting into object

Here is the server side code I am trying to send json
$x = array();
$timestamp = strtotime('22-09-2008');
$x["x"] = $timestamp;
$x["y"] = 22;
$val = '[{ "name": "weight", "dataPoints": ['.json_encode($x).'] }]';
echo json_encode($val);
So output for above code looks like
"[{ \"name\": \"weight\", \"dataPoints\": [{\"x\":1222041600,\"y\":22}] }]"
Below is the client side code I get the data via Jquery getJSON
var jqxhr = $.getJSON( "https://domain/gettracker.php?id="+id, function(data) {
console.log(data);
})
I suppose getJson converts json to object automatically , but it logs the raw json like below
"[ { name: "weight", dataPoints: [{"x":1222041600,"y":22}] } ]"
I tried to do json parse , but i get error.
I guess I am not sending the data properly via php.Can some one guide me ?
Your JSON string is not valid - the property names should be enclosed in double quotes - ", and you don't need to encode the string again.
$val = '[{ "name": "weight", "dataPoints": ['.json_encode($x).'] }]';
echo $val;
Or better yet, use json_encode to create the string for you:
$data = array(
'name' => 'weight',
'dataPoints' => $x
);
echo json_encode($data);

Change JSON_Encode output format (Brackets and Commas)

I have an array that is created in PHP, and then encoded into my javascript via JSON.
The Array is defined here:
$stmt -> bind_result($match_id, $hero, $mmr);
while($stmt -> fetch()){
$grapharray[] = array($hero => $mmr);
}
and JSON encoded here:
$grapharray_labelled = array(
"label" => "MMR Over time",
"data" => $grapharray
);
and here:
var graphdata = <?php echo JSON_encode($grapharray_labelled); ?>;
The output when I run my webpage is that graphdata =:
{
"label":"MMR Over time",
"data":[
{"Rubick":6524},
{"Lion":6550},
{"Magnus":6565},
{"Keeper of the Light":6566}
]
}
However I would like it to be like this:
{
"label":"MMR Over time",
"data":[
["Rubick", 6524],
["Lion", 6550],
["Magnus", 6565],
["Keeper of the Light", 6566]
]
}
Reason:
I would like to change the format because I am trying to get flot to work, and flot accepts an array of arrays as the datatype.
Otherwise: Is there a better way to transfer an array from PHP to JavaScript with my desired format?
Change this:
$grapharray[] = array($hero => $mmr);
TO:
$grapharray[] = array($hero, $mmr);

Cannot access Object key "#attributes" for itunes RSS feed

I'm trying to parse an itunes RSS feed by converting it to JSON via php and then inserting it with jQuery .ajax.
First is the php
<?php
$url = "http://schoolceoshow.libsyn.com/rss";
$fileContents = file_get_contents($url);
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
$simpleXml = simplexml_load_string($fileContents);
$json = json_encode($simpleXml);
echo $json;
?>
Now the javascript
var root = location.origin + "/";
$.ajax({
url:root + "php/podcast.php",
type:"GET",
data:"json",
success:function(data){
var dataObject = $.parseJSON(data);
console.log(dataObject.channel.item[0].enclosure);
},
error:function(){
console.log("failed");
}
});
What that logs out is
Object {#attributes: Object}
#attributes: Object
length: "25583209"
type: "audio/mpeg"
url: "http://traffic.libsyn.com/schoolceoshow/SchoolCEOShow-007.mp3"
My only issue here is accessing the #attributes key. How do I access a key with an # symbol? Thanks!
The solution is to access the object with bracket notation. What I've added to my code is
var enclosure = dataObject.channel.item[0].enclosure;
console.log(enclosure["#attributes"]);
Answer was found at : Parsing JSON w/ # at sign symbol in it (arobase)

split ajax json response errors in each field

i used till now AJAX post with normal dataType 'html' , now i convert it and using dataType 'json' ,
Now before i used json i split response errors with for each span next to the input field .
this is my old ajax succses split errors code using normal datatype 'html' :
success:
function(data){
var data_array = split('*');
for(var i=0; i<data_array.length-1; i++)
{
messgae_array = data_array[i].split(':');
$("#"+messgae_array[0]+"_error").html(messgae_array[1]);
$("#"+messgae_array[0]).css({"border":"1px solid red"});
}
}
this is my input on the form
<input type="text" id="uname" name="uname" value="" class="inplaceError" />
<span id="uname_error"></span>
i have more inputs i puted just ex how it look..
so every input i have span that holds the errors from the ajax response.
and now the problem is my old code know handle html response and not json response , i am javascript/ajax/json newbie , and i dont know how to change the split code so work with json response and not normal html response , any help please?
Edit:
i fire the errors like this :
if(isset($_POST['p']) && !empty($_POST['p']))
{
if($password == $retype)
{
$random_salt = hash('sha512', uniqid(mt_rand(1, mt_getrandmax()), true));
// Create salted password (Careful with the chilli)
$password = hash('sha512', $password.$random_salt);
}
else
{
$message['password']=' password not match';
}
and so on .
$message['email']=' wrong email';
and my foreach json array for the errors :
foreach($message as $key => $val) {
$return = array('error' => $key, 'message' => $val );
echo json_encode($return);
}
so somthing is wrong here with the foreach for the errors its fire wrong as the ajax response code any idea?
You should not have to split strings in your data. If it is in the correct JSON format, you can access it easily using object notation (also possible via array notation):
var json = '{
"someVar":true,
"error":"my fatal error message"
}';
var obj = JSON.parse(json);
alert(obj.error);
This is why JSON was created, for ease of access and use. If you're still going to edit and split strings manually to read data from your JSON, you're doing it wrong.
EDIT:
Use nested json, if you need to identify and organise your messages.
var json = "errors": [{
"id": "001",
"field": "textfield1",
"message": "message1."
},
{
"id": "002",
"field": "textfield2",
"message": "message2."
}];
var obj = JSON.parse(json);
You can now apply styles to these fields, and display the messages:
foreach(obj.errors as err) {
$("#"+err.field).html(err.message);
$("#"+err.field).css({"border":"1px solid red"});
}
success:function(data)
{
// consider your data is like this JSON string
// var data= [{"error":"uname","message":" wrong pass."},{"error":"email","message":" wrong name"}];
// instead of this
// var data_array = split('*');
// use this
//change your json parser to this
var data_array = JSON.parse(data);
for (var i in data_array )
{
$("#"+data_array[i].error+"_error").html(data_array[i].message);
$("#"+data_array[i].error).css({"border":"1px solid red"});
}
}

Categories

Resources