I'm having trouble reading the JSON data from a venues search. Here is my code:
xmlhttpRC = new XMLHttpRequest();
url = "https://api.foursquare.com/v2/venues/explore?ll="+pointStrr+"&oauth_token=V5PI2GJ0KDOVH2GAHNHJ5DVLMRKNF440FR1N1HPG0XHX2OBQ&v=2015643&
callback=JSONP";
xmlhttpRC.open("GET", url, true);
xmlhttpRC.onreadystatechange = recCb;
xmlhttpRC.send(null);
//return recommendedArr;
}
function recCb(data){
//console.log(data);
if(xmlhttpRC.readyState == 4){
if(xmlhttpRC.status == 200){
var recRes = xmlhttpRC.response;
console.log(recRes);
//console.log(recRes);
console.log(recRes.meta.code);
}
}
}
I get the reponse I expect from the server, and firebug shows me that a JSON object is returned, but I am not sure how to access the data inside from here.
console.log(recRes.meta.code) returns the error:
"recRes.meta is undefined"
Where am I going wrong?
I want to access the venues information but I am just using meta.code as a simple test.
This is probably really simple but I'm stumped!
Thanks in advance,
Ross.
You need to parse JSON. Modern browsers have JSON.parse built in, older versions of IE etc. do not - you can theoretically use eval(response) but it creates a security hole.
There is a library to parse it if you cannot depend on users having modern browsers.
var decodedResp = JSON.parse(recRes);
if (decodedResp.meta.code === ...)
JSON-object is just a representation of an JS-object, see; it should be parsed first.
Related
I am trying to parse a list of JSON files iteratively. Using PHP I have managed to compile the list of JSON files in a directly into a a single JSON object. Now I would like to parse each of these objects and output a property from each of them in HTML. I am sure that the JSON I am initially passing works. Any ideas? here is the error and the function.
$(document).ready(function(){
console.log("something")
for(var i = 2; i < Object.keys(jsTrips).length; i++){
var data_file = "http://localhos:8080/trips/" + jsTrips[i];
var currTrip = JSON.parse(data_file)
document.getElementsByClassName(i).innerHTML = currJSON.start_time;
}
console.log("finished")
});
ignore the missing t in localhost. The problem persists even when the typo is fixed
Thanks in advance!!
UPDATE:
The Javascript object jsTrips is formatted like this:
{2: name.json, 3:name.json, 4:name.json}
The the JSON files named in jsTrips are formatted like this:
{start_time: some start time, coords: [{lat: ##, long: ##}, {lat: ##, long: ##}...], end_time: some end time}
To address the error you see:
SyntaxError: JSON.parse: Unexpected character at Line 1 Column 1
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. You are feeding it a URL when it is expecting [ or { as the first character. So h causes a Syntax Error.
Assuming you define the Object jsTrips someplace in your code, and this is a more basic object, I would suggest the following:
$(function(){
console.log("Start jsTrips");
var i = 0;
$.each(jsTrips, function(k, v){
if(i >= 2){
$.getJSON("http://localhos:8080/trips/" + v, function(data_file){
$("." + i).html(data_file.start_time);
});
}
i++;
}
console.log("Finished");
});
This code also assumes there are HTML Elements with attributes like class="2". It would be better to update your Post with an example of the Objects and an example of the JSON being returned.
Now, if the Index of the Object is the class name, then it might look more like:
$.getJSON("http://localhos:8080/trips/" + v, function(data_file){
$("." + k).html(data_file.start_time);
}
Again, need to know what you're sending and what you expect to get back.
jQuery.getJSON() Load JSON-encoded data from the server using a GET HTTP request.
See More: https://api.jquery.com/jquery.getjson/
Update
Now using JSONP method via $.getJSON(), this will help address CORS:
$(function() {
var jsTrips = {
2: "file-1.json",
3: "file-2.json",
4: "file-3.json"
};
console.log("Start jsTrips");
$.each(jsTrips, function(k, v) {
var url = "http://localhos:8080/trips/" + v;
console.log("GET " + url);
$.getJSON(url + "?callback=?", function(json) {
$("." + k).html(json.start_time);
});
});
console.log("Finished");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
As you can see, this builds the new URL from your jsTrips as expected. You can get the start_time from the JSON directly. You don't need to parse it when JSON is expected.
In regards to the new CORS issue, this is more complicated. Basically, you're not calling the same URI so the browser is protecting itself from outside code.
Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin. A web application makes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, and port) than its own origin.
An example of a cross-origin request: The frontend JavaScript code for a web application served from http://domain-a.com uses XMLHttpRequest to make a request for http://api.domain-b.com/data.json.
For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request HTTP resources from the same origin the application was loaded from, unless the response from the other origin includes the right CORS headers.
See more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS & https://www.sitepoint.com/jsonp-examples/
If you are unable to change the port being used for the target JSON files, which I suspect is creating the CORS issue, you can consider using JSONP method versus GET method. Comment and let me know if this is the case, and I can update the answer. Example included in update.
Hope that helps.
This will not probably be a complete answer, because I don't really understand the question. But maybe it will help.
You told us you compiled in PHP one file from several JSON files, in general, if you have object in JSON file, it will look like { ...some key-values here... }, if you have array there, it will be [ ...some key-values here... ].
So when you compile several files with objects into one, you'll get {...some key-values here...} {...some key-values here...} and JSON does not know how to parse those, it will throw error:
console.log(JSON.parse('{"key": "value"}{"key": "value"}'))
This will work just fine, only one object there:
console.log(JSON.parse('{"key": "value"}'))
So, if for some reason you really need to compile several JSON files into one, there is a solution - to make such resulting file with new lines as separators. Than in JS you can split your file by new line, and parse each line without issues.
Like so:
const arrayOfJSONs = Array(10).fill(null).map((_,i) => JSON.stringify({key: i, keyXTen: i * 10}))
// then you join them in one big file with \\n new lines as separators
const oneBigFile = arrayOfJSONs.join("\n");
console.log("oneBigFile:\n", oneBigFile)
// on the client you get your one big file, and then parse each line like so
const parsedJSONs = oneBigFile.split("\n").map(JSON.parse)
console.log("parsedJSONs\n", parsedJSONs)
JSON.parse take string input
Javacript fetch
$(document).ready(function(){
console.log("something")
for(var i = 2; i < Object.keys(jsTrips).length; i++){
var data_file = "http://localhos:8080/trips/" + jsTrips[i];
fetch(data_file).then((res) => res.json())
.then((currJSON) => {
// document.getElementsByClassName(i).innerHTML = currJSON.start_time;
// update your DOM here
})
}
console.log("finished")
});
JQuery $.getJSON
$(document).ready(function(){
console.log("something")
for(var i = 2; i < Object.keys(jsTrips).length; i++){
var data_file = "http://localhos:8080/trips/" + jsTrips[i];
$.getJSON(data_file, (currJSON) => {
// document.getElementsByClassName(i).innerHTML = currJSON.start_time;
// Update DOM here
});
}
console.log("finished")
});
I have this function in google script that fetches a JSON from the web, but it fails when i try to execute it, citing:
SyntaxError: Unexcpected character in string: '\''
Script:
function getTheFeed(url){
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var Jdata = JSON.parse(json);
Jdata = json;
return Jdata;
}
I've tested the URL, by importing it in a string and doing JSON.parse on it, and i get no errors in Google Chrome.
Any other ideas?
UPDATE: After doing Logger.Log turns out the JSON is being cut after 8KB of response. Nothing conflicting at the place the request ends...
Still looking for a response...
Try to use alert(url) and see what you really get.
It could be an escaping issue which sometimes browsers handle properly when you enter it directly in the address bar.
EDIT:
Different browsers have different limits. But generally the limit is around 2,000 characters for the GET method of a URL.
See:
What is the character limit on URL
I am sending an AJAX request to server and retrieving a response as a json object from the server with javascript code to my android application. I know the key values of the json object(ID, name, status, etc.) but I do not know how to get their values.(100, Mark, success, etc.) I need those data for processing for some other task. Can someone please tell me how to extract data from that json object. When I use alert(http.responseText); as follows I get the json object displayed. I need to get the values out of it.
method used to receive response
http.onreadystatechange = function() { //Handler function for call back on state change.
if(http.readyState == 4) {
alert(http.responseText);
json object I receive
{"header": {"ID":100,"name:"Mark"},"body":{"status":"success"}}
You have to convert The string to an object by doing var response=JSON.parse(http.responseText);
Just treat it like any object - console.log(response['name'])
You need to convert it to a JavaScript object using JSON.parse:
var obj = JSON.parse(http.responseText);
Since some legacy browsers do not have native JSON support you should include json2.js to shim it for those browsers.
you will have to eval the http.responseText to get the json object...
but using eval is not recommended, so you can use the json2 library to parse the text into json object..
or else you can even use the library like jquery and use function parseJSON to get it converted to json object
I am trying to read the finance info from the google page into a json object.
Code is below:
try {
$.getJSON("http://finance.google.com/finance/info?client=ig&q=NSE:GOLDBEES&jsoncallback=?",function(data){
alert(data);//var jsondata = data;
//jsonobj = $.parseJSON(jsondata);
//alert(jsonobj[0].id);
});
} catch(e) {
alert(e.toString());
}
However I keep getting this error all the time on firebug
invalid label
"id": "4052464"
Is there any way this info can be read. My ultimate goal is to create a windows 7 gadget that doesnt use server side scripting and can be used from any Windows 7 system.
Appreciate all the help.
John
Response isn't valid JSON (response is prefixed with //), so jQuery won't be able to parse it correctly anyway.
To solve change &jsoncallback=? to &callback=?
so
$.getJSON("http://finance.google.com/finance/info?client=ig&q=NSE:GOLDBEES&callback=?", function(data) {
alert(data)
});
The response from Google has two leading /'s, making the response invalid JSON... for some reason.
Because of this, you cannot use jQuery.getJSON, as it expects a JSON response. Instead, you should use jQuery.get, and parse the JSON yourself after removing the two leading slashes.
jQuery.get('http://finance.google.com/finance/info?client=ig&q=NSE:GOLDBEES&jsoncallback=?', function (string) {
var validJson = string.slice(2);
var obj = jQuery.parseJSON(validJSON);
// use obj
});
Two additional points:
No JSONP is being used, so you don't need the jsoncallback=? in your request URL
The Windows Sidebar has been retired, so you cannot publish you finished gadget to the official gallery.
Question:
I'm trying to use JSON accross domains, but all i find is JSON parsers, which I don't need...
I've read that it's possible to do cross-domain requests with JSON,
but so far, all I see is implementations that use XMLHttpRequest...
- which means you can't use cross-domain requests, at least not outside IE 8...
I've been on http://www.json.org/, but all I find is either parsers or useless.
The best I've found with google so far is
http://devpro.it/JSON/files/JSONRequest-js.html
but this is rather a mess, doesn't work cross domain, and intra-domain neither - or rather not at all...
var the_object = {};
var http_request = new XMLHttpRequest();
http_request.open( "GET", url, true );
http_request.onreadystatechange = function () {
if ( http_request.readyState == 4 && http_request.status == 200 ) {
the_object = JSON.parse( http_request.responseText );
}
};
http_request.send(null);
What you can do cross-domain is inject a script include:
var s = document.createElement('script');
s.src = 'http://someotherdomain/getMeMyJs.aspx?parameter=value';
s.onload = someOptionalCallback;
s.type = 'text/javascript';
if(document.getElementsByTagName('head').length > 0)
document.getElementsByTagName('head')[0].appendChild(s);
Now, the code returned by that request will be executed immediately. If you want for that to interact with your code, you can make sure that it's being returned with all data wrapped in a function call:
jsonCallback({ object: json, whatever: value });
You can use that to build APIs, where you pass the name of a callback function as a request querystring parameter. Here's an example of such an API
JSON is just a serialization method. There is no relation whatsoever between the method of the serialization and the question of whether or not the browser will try to stop you from accessing data across domains. (This explains why you are only finding parsers - there is nothing to JSON, except encoding and decoding it).
XMLHTTPRequest is just named XML HTTPRequest. It doesn't really have anything to do with XML. It can be used to send text data, data encoded in JSON, or any others serialization method.
There are several methods to access data cross domain. one described in David Hedlund's answer. Others can be found in answers to similar questions (see here and here).