How can I read a .json file without jQuery in JavaScript? - javascript

I am only asking the question because I've spent the last 2 days probably reading through countless other questions that are similar and tutorials and still can't get this to work.
I have a local .json file that I want to load up and parse with JavaScript. The file is called 'fakeData.json'. Its format is as such:
{"UIGroup": {"Parent": null, "Type": "public"}}
I'm using this to try to load the file:
<script src="fakeData.json"></script>
I am using this to try to parse the file:
var jsonData = JSON.parse('fakeData.json');
I am getting these errors:
Uncaught SyntaxError: Unexpected token : fakeData.json:1
Uncaught SyntaxError: Unexpected token ILLEGAL : planetPage.html:11
May someone please help me, thanks.

If you want it as simple as it gets, then I would prefix your json content with
var jsonData = {"UIGroup": {"Parent": null, "Type": "public"}}....
which turns your file into a valid js file and then load it with
<script src="fakeData.json.js"></script>
after that, jsonData will have the required content because of literal object notation.
There is no way that you can load a json file into your page otherwise without ajax/httprequest.

You need to get the JSON text into a string variable before you can parse it.
This is generally achieved using the XMLHttpRequest object.
<script src="fakeData.json"></script> will attempt to parse the JSON as JavaScript. This will either throw an error (as it does in your case) or create a data structure and then immediately discard it as it isn't assigned there.

var jsonData;
function reqListener () {
jsonData = JSON.parse(this.responseText);
console.log(jsonData);
};
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "fakeData.json", true);
oReq.send();

If you want to keep it all inline, with a JSON string, and access the object directly you could do something like this:
// copy all the JSON text from the file an keep store it in a local string variable.
var jsonString = '{ "UIGroup": { "Parent": null, "Type": "public" }}';
// parse the string into a JavaScript object
var jsonObj = JSON.parse(jsonString);
// access the object as you usually would
alert(jsonObj.UIGroup.Type);
Fiddle

Related

GetMethod.getResponseBodyAsString() to xml object

using Javascript HttpClient i am running a get method on WebService which works fine and then i store Response in a variable resp_va as shown below.
snip from code below.
var httpGetMethod = new GetMethod(url);
httpClient.executeMethod(httpGetMethod);
var statuscode = httpGetMethod.getStatusCode();
var resp_va = httpGetMethod.getResponseBodyAsString();
although output is in XML Format but to me Looks like it is string and therefore i am unable to parse it. Question is how can i convert "resp_va" in XML object before parsing it further?

How to retrieve JSON data located in a different file

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
}

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

javascript json post using variables

I'm trying to get an Xmlhttp.response from a website, specifically with this part of code:
var apiUrl = "http://somesite/someapicall/correctapiKey";
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", apiUrl, false);
xmlHttp.setRequestHeader("Content-Type", "application/json");
var data {
"username": username,
"password": hashedPass,
"someOption": "true",
"someOtherOption": "true"
}
xmlHttp.send(data);
var response = xmlHttp.responseText;
var parsed = eval('(' + response + ')');
If i put in the actual strings in "username": & "password" instead of using the variables the code does work. with the variables it fails.
I'm probably missing something small again, but i really can't see it and i'm breaking my head over it since this afternoon :(
anyone ? please...
edited: the username and the hashed pass are given as variables with known correct values. changed the code to reflect the use of the variables
This:
var apiUrl = "http://somesite/someapicall/correctapiKey";
uses an absolute URI, which implies you may be performing a cross-origin request. Make sure you aren't going to run into problems with the Same Origin Policy. (See also ways to circumvent it).
This:
var data {
"username": username,
"password": hashedPass,
"someOption": "true",
"someOtherOption": "true"
}
… is a syntax error. You need an = sign after data.
If the last two options are supposed to be booleans, they shouldn't have quotes around them.
You should avoid automatic semi-colon insertion. Put a ; after the }.
This:
xmlHttp.send(data);
… will convert data to a string by calling toString() on it. This will give you [Object object].
If you want to send JSON, then you must convert the JavaScript object to JSON:
data = JSON.stringify(data);
This:
var parsed = eval('(' + response + ')');
is evil, slow, hard to debug and potentially dangerous if you get an expected response. Use a JSON parser instead:
var parsed = JSON.parse(response);

I keep getting "Uncaught SyntaxError: Unexpected token o"

I'm trying to learn some html/css/javascript, so I'm writing myself a teaching project.
The idea was to have some vocabulary contained in a json file which would then be loaded into a table. I managed to load the file in and print out one of its values, after which I began writing the code to load the values into the table.
After doing that I started getting an error, so I removed all the code I had written, leaving me with only one line (the same line that had worked before) ... only the error is still there.
The error is as follows:
Uncaught SyntaxError: Unexpected token o
(anonymous function)script.js:10
jQuery.Callbacks.firejquery-1.7.js:1064
jQuery.Callbacks.self.fireWithjquery-1.7.js:1182
donejquery-1.7.js:7454
jQuery.ajaxTransport.send.callback
My javascript code is contained in a separate file and is simply this:
function loadPageIntoDiv(){
document.getElementById("wokabWeeks").style.display = "block";
}
function loadWokab(){
//also tried getJSON which threw the same error
jQuery.get('wokab.json', function(data) {
var glacier = JSON.parse(data);
});
}
And my JSON file just has the following right now:
[
{
"english": "bag",
"kana": "kaban",
"kanji": "K"
},
{
"english": "glasses",
"kana": "megane",
"kanji": "M"
}
]
Now the error is reported in line 11 which is the var glacier = JSON.parse(data); line.
When I remove the json file I get the error: "GET http://.../wokab.json 404 (Not Found)" so I know it's loading it (or at least trying to).
Looks like jQuery takes a guess about the datatype. It does the JSON parsing even though you're not calling getJSON()-- then when you try to call JSON.parse() on an object, you're getting the error.
Further explanation can be found in Aditya Mittal's answer.
The problem is very simple
jQuery.get('wokab.json', function(data) {
var glacier = JSON.parse(data);
});
You're parsing it twice. get uses the dataType='json', so data is already in json format.
Use $.ajax({ dataType: 'json' ... to specifically set the returned data type!
Basically if the response header is text/html you need to parse, and if the response header is application/json it is already parsed for you.
Parsed data from jquery success handler for text/html response:
var parsed = JSON.parse(data);
Parsed data from jquery success handler for application/json response:
var parsed = data;
Another hints for Unexpected token errors.
There are two major differences between javascript objects and json:
json data must be always quoted with double quotes.
keys must be quoted
Correct JSON
{
"english": "bag",
"kana": "kaban",
"kanji": "K"
}
Error JSON 1
{
'english': 'bag',
'kana': 'kaban',
'kanji': 'K'
}
Error JSON 2
{
english: "bag",
kana: "kaban",
kanji: "K"
}
Remark
This is not a direct answer for that question. But it's an answer for Unexpected token errors. So it may be help others who stumple upon that question.
Simply the response is already parsed, you don't need to parse it again. if you parse it again it will give you "unexpected token o" however you have to specify datatype in your request to be of type dataType='json'
I had a similar problem just now and my solution might help. I'm using an iframe to upload and convert an xml file to json and send it back behind the scenes, and Chrome was adding some garbage to the incoming data that only would show up intermittently and cause the "Uncaught SyntaxError: Unexpected token o" error.
I was accessing the iframe data like this:
$('#load-file-iframe').contents().text()
which worked fine on localhost, but when I uploaded it to the server it stopped working only with some files and only when loading the files in a certain order. I don't really know what caused it, but this fixed it. I changed the line above to
$('#load-file-iframe').contents().find('body').text()
once I noticed some garbage in the HTML response.
Long story short check your raw HTML response data and you might turn something up.
SyntaxError: Unexpected token o in JSON
This also happens when you forget to use the await keyword for a method that returns JSON data.
For example:
async function returnJSONData()
{
return "{\"prop\": 2}";
}
var json_str = returnJSONData();
var json_obj = JSON.parse(json_str);
will throw an error because of the missing await. What is actually returned is a Promise [object], not a string.
To fix just add await as you're supposed to:
var json_str = await returnJSONData();
This should be pretty obvious, but the error is called on JSON.parse, so it's easy to miss if there's some distance between your await method call and the JSON.parse call.
Make sure your JSON file does not have any trailing characters before or after. Maybe an unprintable one? You may want to try this way:
[{"english":"bag","kana":"kaban","kanji":"K"},{"english":"glasses","kana":"megane","kanji":"M"}]
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
JSON.stringify(tempActivity, getCircularReplacer());
Where tempActivity is fething the data which produces the error "SyntaxError: Unexpected token o in JSON at position 1 - Stack Overflow"

Categories

Resources