How to retrieve JSON data located in a different file - javascript

I have 6 json files in the same directory as my index.htm. Each json structure has saved game data in it. I want to let the user choose a file and load its associated json data structure. How can I go about retrieving that data?
I tried using
var myjson = new Object();
$.getJSON("myJSON.json", function(json) {
myjson = JSON.stringify(json);
console.log(myjson);
});
This gives me an XMLHttpRequest error (cross-origin request not supported).

Your execution is fine -- though like the comments on your post suggest, you need to change the protocol you're using. Really just load the HTML page using http://127.0.0.1/mypage.html instead of file://home/website/mypage.html and you can likely keep your javascript the same.
Aside from this, you might want to consider the data in your myJSON.json file. I noticed if the JSON data contains function definitions then it will cause $.ajax() or in this case $.getJSON() to throw a parse error.
So this will not work
{
"json" : function () {
alert("HI");
},
"hello" : 432
}
But this will work
{
"json" : "5",
"hello" : 432
}

Related

I have json file on local computer i want to use that file in javascript how can i use that in js

Following is the code snippet which i am trying
var json = require('dictonery.json'); //(with path)
console.log(json);
$.getJSON is asynchronous. See http://api.jquery.com/jQuery.getJSON/
You should do
$.getJSON("test.json", function(json) {
console.log(json);
// this will show the info it in firebug console
});
OK, so from your comments I assume you have the following scenario: You have a server somewhere running your code and you have a local machine where the JSON file is stored. That won't work, if the local machine is not running a web server allowing you to load the JSON to the machine running the code. You could do this in that case e.g. by using PHP's file() function or via an Ajax call. I'd rather recommend to upload it first, so all files are in the same file system.
If you create the JS from a PHP enabled file you could do the following:
var json = '<?php require('dictonery.json') ?>'; //(with path)
console.log(json);
var jsonObj = JSON.parse(json);
console.log(jsonObj);
The require loads the file holding your JSON data (given that it is accessible) and puts it into the js file so that it ends up in a string variable. The JSON.parse creates a Javascript object from this string, so that you can actually use the data.

save parsed JSON as obj

first question ever, I'm trying to parse a JSON file stored within the same file directory on my webhost as my html file that runs the javascript to parse it, I've added a console.log to debug and confrim that the file is being caught by the 'get' to ensure that I am able to 'get' the file throgh the use of jquery getJSON, in the callback i've tried to create a function that re-defines a global variable as an object containing the parsed data, but when I try to inject it into a document.getElemendtById('example').innerhtml = tgmindex.ToughGuys[1].name;
it returns a error "Uncaught TypeError: Cannot read property '1' of undefined"
here's my js/jquery
var tgmIndex;
$(document).ready(function () {
$.getJSON("http://webspace.ocad.ca/~wk12ml/test.json",function(data){
console.log( "success" );
tgmIndex =$.parseJSON;
document.getElementById('tgm1').innerHTML= tgmIndex.ToughGuys[1].name;
});
});
and here is whats contained in the JSON (i made sure to try linting it first and it's a valid json)
{"ToughGuys":[
{"name":"Ivan", "position":"Executive"},
{"name":"Little Johnny", "position":"Intern"},
{"name":"Beige Cathy", "position":"Executive"},
{"name":"Stan", "position":" original Intern"}
]}
You're setting tgmIndex to the parseJson function.
Should be doing tgmIndex =$.parseJSON(data);
Presumably your service is returning application/json. Therefore data already contains the json.
tgmIndex = data;
Then... "Tough Guys" is what you should be indexing. Not "ToughGuys"
Your example JSON is wrong in your question. If I go to
http://webspace.ocad.ca/~wk12ml/test.json
I see:
{"Tough Guys":[
{"name":"Ivan", "position":"Executive"},
{"name":"Little Johnny", "position":"Intern"},
{"name":"Beige Cathy", "position":"Executive"},
{"name":"Stan", "position":"Intern 0"}
]}
See "Tough Guys" There's your problem.
document.getElementById('tgm1').innerHTML= tgmIndex['Tough Guys'][1].name;
If data for some reason isn't JSON:
tgmIndex = $.parseJSON(data);

using and storing json text in JavaScript

I'm making a 2D, top-down Zelda-style web single player rpg...
I'd like to store dialog in JSON format...
Currently I'm getting the json as an external javascript file. The json is stored as such in js/json.js:
function getJson() {
var json = {
"people" :
[
{//NPC 1 - rescue dog
etc...
Then I use it in my main game javascript file as such <script src="js/json.js"></script>..`
var json = getJson();
Then use it as such:
Labels[index].text = json.people[index].dialogs.start.texts[0];
Does it matter if I keep the json as a js file in a javascript function? Or should it be stored as a .txt file then parsed?
Thanks!
It does not matter but JSON data is also JavaScript so store it as .js and later on you can add more data related functions to it if needed, btw your data file already has a getJSON function so it doesn't make sense to store it as .txt
On the other hand if an API is serving this data it need not have any extension at all.
It's better off storing the data in pure JSON format and retrieving it via jQuery.getJSON() or an XMLHttpRequest, if you're using vanilla JavaScript. Otherwise, it looks like you're adding getJson() to the global scope, which may result in a conflict if you have another getJson() defined elsewhere.
So you could have a dialog.json that looks almost the same as what you have now, just without the unnecessary getJson() function:
{
"people" :
[
{//NPC 1 - rescue dog
...
}
]
}
If you choose to use jQuery:
var dialog;
$.getJSON('json/dialog.json', function(data) {
dialog = data;
// Asynchronous success callback.
// Now dialog contains the parsed contents of dialog.json.
startGame();
});
Keeps your data separate from your logic.

AJAX responseXML

i have a problem regarding the responseXML of ajax..
I have this code from my callback function:
var lineString = responseXML.getElementsByTagName('linestring')[0].firstChild.nodeValue;
However, the linestring can only hold up to 4096 characters max.. the remaining characters are rejected.
I dont know what to use to get all the values that the lineString
returns. its quite a big data thats why I thought of using the responseXml
of AJAX, BUT turned out it still cannot accomodate everything.
My linestring consists of lines from a logfile which I concatenated and just
put line separator. I need to get this data in my form so that is why after reading from the php, i send it back via AJAX
Do you have suggestions guys.
XML adds a lot of extra markup for most ajax requests. If you are expecting some kind of list with data entities, sending them in a JSON format is the way to go.
I used JSON to get quite huge arrays with data.
First of all, JSON is just Javascript Object Notation meaning that the Ajax Request would request a String which will actually be evaluated as a Javascript object.
Some browsers offer support for JSON parsing out of the box. Other need a little help. I've used this little library to parse the responseText in all webapps that I developed and had no problems with it.
Now that you know what JSON is and how to use it, here's how the PHP code would look like.
$response = [
"success" => true, // I like to send a boolean value to indicate if the request
// was valid and ok or if there was any problem.
"records" => [
$dataEntity1, $dataEntit2 //....
]
];
echo json_enconde($response );
Try it and see what it echos. I used the php 5.4 array declaration syntax because it's cool! :)
When requesting the data via Ajax you would do:
var response
,xhr = getAjaxObject(); // XMLHttp or ActiveX or whatever.
xhr.open("POST","your url goes here");
xhr.onreadystatechange=function() {
if (xhr.readyState==4 && xhr.status==200) {
try {
response = JSON.parse(xhr.responseText);
} catch (err) {
response = {
success : false,
//other error data
};
}
if(response.success) {
//your data should be in response
// response.records should have the dataEntities
console.debug(response.records);
}
}
}
Recap:
JSON parsing needs a little help via JSON2 library
PHP can send maps as JSON
Success boolean is widely used as a "successful/unsuccessful" flag
Also, if you're into jQuery, you can just set the dataType : "json" property in the $.ajax call to receive the JSON response in the success callback.

Json object in jquery can't be read?

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.

Categories

Resources