parsing json response - javascript

I'm calling a REST webservice and getting JSON format as a result. I'm calling rest service from another domain than mine. How can I parse this?

To answer the question you asked: There is a long list of parsers, including several for JavaScript, at the bottom of http://json.org/
If your question is actually: "How can I read JSON data from another domain with client side JavaScript in the browser?", then you can either fetch it using a proxy on the same domain as the page, or you can provide the data using JSON-P instead.

<script type="text/javascript" src="http://www.json.org/json2.js"></script>
var myObject = JSON.parse(myJSONtext);
or use jQuery
$.getJSON('http://twitter.com/users/usejquery.json?callback=?', function(json) {
alert(json.followers_count);
});
if you need only parsing jQuery also can do this:
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

Are you getting the json result? Most implementations have protection agains cross site scripting and will only allow a request back to the original host of a page.
Could you please post some example code for your current implementation.

Related

get the geolocation from IP , with "ipinfodb"

i know good javascript but totally novice in json and need to do the following:
get the geolocation from IP , with "ipinfodb"
like this response:
OK;;174.88.229.95;CA;CANADA;QUEBEC;MONTREAL;H1A 0A1;45.5088;-73.5878;-04:00
i found many codes for that but all seem to be complicate and long with more options like saving the results in cookies
i want the least necessary code to retrieve those informations
for saving them in cookies and more i want to care for it my self after.. (i don't like to put code i dont understand)
the best would be a simple function that returns this information as string or array, like this
function getLocFromIP(IP){
(js + json code)
return result;
}
much thank in advance
thank you all for responding i was trying to filter out the solution, and it works but i'm not yet well satisfied of the result..
i gonna reformulate my question here:
is there i can retrive the geo location from ip with simplest way (javascript) that means without json or jquery..
ajax would be perfect but it doesnt work inter domain (different domains)
thanks again
OK;;174.88.230.88;CA;CANADA;QUEBEC;MONTREAL;H1A 0A1;45.5088;-73.5878;-04:00
The example you posted isn't valid JSON (you can check if something is valid JSON somewhere like here). That said, looking at the ipinfodb website they appear to have a way to get JSON output using their API (see here).
Once you have valid JSON, you can use JSON.parse. See here for some examples on using it.
So the general idea is
function getLocFromIP(IP){
//(js code to use ipinfodb API to get valid JSON reponse)
//(js code using JSON.parse to parse the received JSON reponse)
//(js code to get whatever you want as the result)
return result;
}
As a side note, if you use jQuery you can also use jQuery.parseJSON to parse JSON (see here) which will be more reliable if you anticipate clients using older browsers that might not support JSON.parse.
IP location XML API requires some query strings like &format=json&callback=? additional to ip address in order to get json.
Then you get json like this:
{
"statusCode": "OK",
"statusMessage": "",
"ipAddress": "175.108.204.0",
"countryCode": "JP",
"countryName": "JAPAN",
"regionName": "TOKYO",
"cityName": "TOKYO",
"zipCode": "214-002",
"latitude": "35.6149",
"longitude": "139.581",
"timeZone": "+09:00"
}
Here is a sample code (thanks to #iveoak for good template):
function getLocFromIP(IP){
//(js code to use ipinfodb API to get valid JSON response)
var url = 'http://api.ipinfodb.com/v3/ip-city/?key=<your_api_key>&ip=' + ip + '&format=json&callback=?';
var response = $.getJSON(url); // using jQuery
//(js code using JSON.parse to parse the received JSON response)
response.then(function (location) {
var info = '<ul>';
for (var key in location) {
info += '<li>' + key + ': ' + location[key] + '</li>';
}
info += '</ul>';
});
//(js code to get whatever you want as the result)
return result;
}
If you do not use jQuery, see How can I open a JSON file in JavaScript without jQuery?.
Sample (using jQuery): http://jsfiddle.net/tokkonoPapa/tevB4/
I post another answer.
This is a pure javascript solution using jsonp. Basically, it's a same concept using <script src="http://api.ipinfodb.com/..."></script>.
So you can accsess from anywhere, and do not need to handle json directly. You can simply get the javascript object.
Here is my demo: http://jsfiddle.net/tokkonoPapa/vCTpK/
UPDATE:
I/F is slightly different what you want. It uses a callback function.
getLocFromIP(ip, function(result) {
// use result
});
and the demo returns:
OK;;175.108.204.0;JP;JAPAN;TOKYO;TOKYO;214-002;35.6149;139.581;+09:00
I hope this basic solution satisfies you.

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
});

Parse External JSON With JQuery $.getJSON?

I want to get a quote from iheartquotes and add it to a div when the page loads. I currently have this code but do not know why it wont work
<script type="text/javascript">
$(document).ready(function() {
$.getJSON('http://iheartquotes.com/api/v1/random?format=json&callback=?', function(data) {
$(".content").html(json.quote);
});
});
</script>
And the HTML in the body
<div class="content">
This will be replaced with a quote
</div>
The URL returns JSON, not JSON-P, so you can't read it cross domain with JS in a browser.
You could do this server side instead, or find a third party proxy that could convert it to JSON-P (perhaps YQL).
Yes i too agree with #Quentin. This is not possible in client-side as you are trying to access another domain due to Same origin policy.
So you can call a webservice / a static webmethod in an aspx page (using page- methods) from javascript and do this server side and get back the results client-side itself, where you can do this cross-domain.
The following code may help you to do this in server-side,
You could use WebClient for that matter:
using (var client = new WebClient())
{
// Define data to be posted
var values = new NameValueCollection
{
{ "key1", "value1" },
{ "key2", "value2" },
};
// Send the POST request
byte[] result = client.UploadValues("http://foo.com", values);
// This will contain the cookie being set
string cookie = client.ResponseHeaders[HttpResponseHeader.SetCookie];
}
Hope this helps...

Retrieving JSON with JQuery

I'm trying to retrieve JSON with JQuery from: http://www.chirpradio.org/json
How do I retrieve, parse and display that JSON in a web page.
I'm new to JSON and JQuery, and the onsite documentation is a bit difficult to follow.
Thanks,
Moemonty
One way to get past the SOP is to use a proxy(which also converts it into JSONP). i.e.:
var url = "http://www.chirpradio.org/json";
jQuery.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22"+url+"%22&format=json&callback=?", function(data){
console.log(data.query.results.json);/*where yahoo puts the json object*/
});
However, I suggest not to query w/sensitive information(it's insecure). Your use with the radio feed is ok though.

how to post a json from javascript?

i want to send a json string from a html webpage using javascript to a WCF.. is there any good tutorial for that?
this is the code i am using
<head>
<title>Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.json.org/json2.js"></script>
<script type="text/javascript">
$(function() {
JSONStringer json = new JSONStringer()
.object()
.key("cno").value("2000")
.key("cname").value("HI")
.key("cmail").value("HI")
.key("cphno").value("9292")
.key("cmailtype").value("Home")
.key("cphnotype").value("Office")
.key("clientno").value("1")
.endObject();
var dat = JSON.stringify(json.serializeArray());
alert("I am about to POST this:\n\n" + dat);
$.post(
frm.attr("action"),
dat,
function(data) {
alert("Response: " + data);
}
);
});
</script>
</head>
let me know where i have to post it to a particular service.. something like specifying the URL
I think you are mixing up java with javascript. Despite their names they are not related to each other in any way. As far as I know, JSONStringer doesn't exist in javascript nor jquery. JSON stands for JavaScript Object Notation, so that means it is very native to the javscript languages (with some subtle differences). Since it's so close it is very easy to parse Json in javascript.
Also, javascript is a dynamically typed language so supplying the type as you did normally results in a parse error. Use firebug or the Chrome console when your code doesn't work. You will see an error when the browser was unable to parse your code.
for the serialization you probably want to use (in a browser that supports JSON and/or with json2.js)
var dat = JSON.stringify({
cno: 2000,
cname: 'HI',
cmail: 'HI',
cphno: '9292',
cmailtype: 'home',
cphnotype: 'Office',
clientno: 1
});
The url goes where you have put frm.attr("action"). I don't see where you create the frm object. I don't think you need a JQuery object for that, document.getElementById is supported in all major browsers and I bet it is faster too.
var myForm = document.getElementById('myformid');
$.post(
myForm.action,
dat,
function(data) {
alert('Response: ' + data);
}
);
Also as far as I know, postdata has to be in query parameter format so perhaps you need to put something like
'myData=' + dat,
Copy/pasting code from the web can get things started quickly but a lot of javascript programmers forget that you have to understand the language first. Don't just blindly copy code, try to understand what happens. Try to solve problems first without a library and discover where you actually need a library.
http://www.learn-ajax-tutorial.com/PassingData.cfm#JSON
Get json.js.
Encode array or object in to json.
Do Ajax.Request to post the json string. Simplez!
That is pretty much all you need, not sure about the WCF side but if it is a proper webservice then all you need is the descriptor to figure out the function names and their parameters.

Categories

Resources