How to get the result in JSON format from google? - javascript

I have tried to query google using my script but my request is going to Google.com page.
What I am looking for is how I can request google for result and out the result on my test html in json format. Here is what I tried:
<html>
<body>
<script type="text/javascript">
function google()
{
var str=document.getElementById('googlebox').value;
str="http://www.google.com/search?hl=en&source=hp&q=" + str + "&aq=f&oq=&aqi=";
var replaced=str.replace(" ","+");
window.location.replace(replaced)
}
</script>
<input type="text" value="Google" id="googlebox"/>
<input type="button" value="Go" onclick="google()"/>
</body>
</html>

You can't.
For any given a URL, a server returns what it returns.
You can't make a server return data in an arbitrary format (or force it to use CORS to grant permission to your script to read that data).

You should look into google's custom search API. It has an option to return data in JSON format.
https://developers.google.com/custom-search/json-api/v1/using_rest

Related

Convert JSON object to string without JSON

This is my server response:
{"names":["Kreisler","Kreisler","Kreisler"]} .
If I use the above JSON response in JavaScript, I am getting an 'object' datatype
as [object Object]. Instead of getting Object type, I want to get the JSON response in string format.
Note: I don't have JSON js from my html.so I will not be able to use
JSON.stringify({"names":["Kreisler","Kreisler","Kreisler"]}).
Or let me know how can I install JSON here.
<!DOCTYPE html>
<html>
#<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
ss = {"names":["Kreisler","Kreisler","Kreisler"]}
document.getElementById("demo").innerHTML = ss;
}
</script>
</html>
<!DOCTYPE html>
<html>
#<button type="button" onclick="myFunction()">Try it</button></br>
<div id="demo"></div>
<script>
function myFunction() {
var ss = JSON.stringify({"names":["Kreisler","Kreisler","Kreisler"]});
document.getElementById("demo").innerHTML = ss;
}
</script>
</html>
There are several possible ways to solve your problem. The first is simply to examine how you are making your request to the server. Chances are that you can stop parsing the response to JSON and instead keep it a string.
If you don't have any control over that portion of the code, you will have to stringify the JSON object. You say that you don't have JSON.stringify available in the browser which is suspicious. window.JSON is a global and doesn't need to be "installed" at all. According to the MDN, window.JSON was available all the way back to IE 8:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON
If you're using a custom browser implementation, the first option is probably your best.

Loading external JSON with Javascript

I'm trying to catch some JSON info from a site.
My first exemple its just a test and work:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$.get("http://www.w3schools.com/jquery/demo_test.asp",function(data,status){
document.write("Data: " + data + "\n<br>Status: " + status);
});
});
</script>
But the problem its in my second example:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$.get("https://btc-e.com/api/2/ltc_usd/ticker",function(data,status){
document.write("Data: " + data + "\n<br>Status: " + status);
});
});
</script>
PS - i'm trying to get the info from the page to use it in a blog :)
External JSON with jQuery means using JSONP. This works by the page returning a Javascript script instead, which calls a function (which you define) with the data you need. You can't get the data as normal JSON. So the response needs to look like this:
json_callback({"ticker":{"high":0.77,"low":0.64,"avg":0.705,"vol":107049.5563,"vol_cur":151754.22482,"last":0.76,"buy":0.766,"sell":0.75811,"server_time":1364653244}});
rather than
{"ticker":{"high":0.77,"low":0.64,"avg":0.705,"vol":107049.5563,"vol_cur":151754.22482,"last":0.76,"buy":0.766,"sell":0.75811,"server_time":1364653244}}
(The function would not be called json_callback, but would have a unique name each time.)
This obviously relies on the server's assistance, so the server needs to be set up to support JSONP. The normal way of indicating this is by adding callback=? to the end of the URL, where ? is the name of the function you want to call. If we try this, you'll see that the script does not change. This indicates that the website does not support JSONP requests, so there is no way of accessing this data using JSONP.
There are various other methods of getting the data. The simplest is probably proxying the data from the external server with your own server.

Reading contents from a JSON url and writing out those contents

I have a url [https://www.inquicker.com/facility/americas-family-doctors.json] that is a JSON data url. How can I access the contents of this url, and write out the values.
The format contains schedules as an array that inside it contains schedule_id, name, and available_times. I have tried various ways of getting the JSON file, but none have worked.
UPDATE:
Well I have got it this far with this code, and it's laying out what looks like objects from the array. So I believe I got the cross site issue under control. I just need to figure out how to access the data now.
<!DOCTYPE html>
<html>
<head>
<title>JQuery (cross-domain) JSONP</title>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$.getJSON('https://www.inquicker.com/facility/americas-family-doctors.json',
function(data){
alert(data.facility);
$.each(data.schedules, function(i, name){
$('#names').append('<li>' + name.available_times[0] + '</li>');
});
});
});
</script>
</head>
<body>
<ul id="names"></ul>
</body>
</html>
Any help, or suggestions will be greatly appreciated, Thanks.
You cannot generally pass an Ajax request across domains. Normally a server will refuse any Ajax calls that don't come from the same source unless it is explicitly configured otherwise. I am guessing that you aren't calling from the same domain, given that you are using a fully-qualified URL. If you own the server, you will have to configure it to accept such calls from your other domain.
If this is not the case, launch the script in Firefox with Firebug running and look at the console output and tell me what error you get if any.
Once you manage to pass the JSON from your server back to the page, you will retrieve it in your JavaScript as a string. You then need to execute this function:
var jsonObject = JSON.parse(jsonString);
where jsonString is the string that you received from your server. jsonObject becomes an object representation of the JSON passed back to the answer that you can access using dot notation.
Try something like :
alert(json.facility);
There is no title json object in the url you have mentioned.
The JSON is already parsed when it comes to your function.
$.get('https://www.inquicker.com/facility/americas-family-doctors.json', function(result){
alert(result.facility); //Do whatever you want here
// result.schedules array is also ready
});

Reaching a data in json using getJSON

I want to get the username's profile image. So i prefer to use twitter api version 1 for this.(The regular version of api is here). But my code doesn't return any data. How can i fix this?
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script>
$(document).ready( function() {
var userPage = "https//twitter.com/jack";
var arr = userPage.split("/");
var username = "";
for(i=3;i<4;i++)
username += arr[i];
var page = 'https://api.twitter.com/1/users/show.json?screen_name='+username;
$.getJSON(page, function(data) {
alert(data.profile_image_url);
});
})
</script>
</head>
<body>
</body>
</html>
Add "&callback=?" to the URL to force jsonp format to get around the Access-Control-Allow-Origin issue.
var page = 'https://api.twitter.com/1/users/show.json?screen_name='+username + "&callback=?";
EXAMPLE
JSONP:
The way JSONP works is simple, but requires a little bit of
server-side cooperation. Basically, the idea is that you let the
client decide on a small chunk of arbitrary text to prepend to the
JSON document, and you wrap it in parentheses to create a valid
JavaScript document (and possibly a valid function call).
The client decides on the arbitrary prepended text by using a query
argument named jsonp with the text to prepend. Simple! With an empty
jsonp argument, the result document is simply JSON wrapped in
parentheses.

Retrieve JSON data from a hidden input

I store JSON data in HTML hidden fields on the server side. Then I'd like to retrieve that data using Javascript and JQuery on the client side. The problem is that I get a JSON string instead of a JSON object.
This is my code on the server side:
<form id="data" style="display: none;">
<input id="channels" type="hidden" tal:attributes="value python: view.context['ChannelManager'].toJSON(view.channels.values())" />
<input id="mediaGroups" type="hidden" tal:attributes="value python: view.context['MediaGroupManager'].toJSON(view.mediaGroups.values())" />
</form>
This is my code on the client side:
copy.channelList = new ChannelTest();
copy.channelList.fromJSONObjectAll($("#data input[id=channels]").val())
So I get JSON string instead of JSON object from this, $("#data input[id=channels]").val().
How could I get JSON object without converting JSON string in JSON object?
Thanks in advance!
JSON.parse(jsonString);
For older browsers that don't have native JSON support, you can simply include json2.js and this will become a usable function.
Or you can skip this step with some server side scripting. You can simply write the JSON into a script tag. It is parsed implicitly by the script tag instead, as raw javascript.
<script type="text/javascript">
var myObj = <%= myJsonString %>;
console.log('we got this value: '+ myObj.myValue);
</script>

Categories

Resources