the JSON works but print an error in console - javascript

I want to show Json data when the href text is clicked.it works but whenever I clicked the href text the console prints "Uncaught SyntaxError: Unexpected token :" in file data.json. why this is happening? I have validate the code in JSONLint.
file:index. html
<html>
<head>
<script src="data.json"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<h1 id="title">Using jQuery to retrieve Json via Ajax</h1>
Get JSON data
</body>
<script>
$(function(){
$("#clickme").click(function(){
$.getJSON("data.json",function(data){
var items=[];;
$.each(data,function(key,val){
items.push('<li id="'+key+'">'+val+'</li>');
});
console.log(items);
$("<ul/>",{
"class":"interest-list",
html:items.join("")
}).appendTo("body");
});
});
});
</script>
</html>
file:data.json
{
"one":"pikachu is awesome",
"two":"squirtle is awesome"
}

The problem is in your data.json file:
you must change your json like this (using [ ] ):
[
{
"one":"pikachu is awesome",
"two":"squirtle is awesome"
}
]
then you must change your js code to use data[0] instead of data:
$.each(data[0],function(key,val){
items.push('<li id="'+key+'">'+val+'</li>');
});
this prevent the console error and all works fine.
p.s.: i suggest to remove the unnedded ; in line 14:
var items=[];;
to
var items=[];

Related

JSON not returning the actual data from the url

I am trying to build a basic covid19 website. the code I am using is only returning [object Object] in the actual data. What I am doing wrong here?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("https://api.covid19api.com/summary", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>
That's because you're trying to append JavaScript object to DOM. Instead, see what data you're getting (as someone mentioned in comments, by console.log) then you can edit your append part accordingly.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("https://api.covid19api.com/summary", function(result){
$.each(result.Countries, function(i, field){
$("div").append("<span>"+JSON.stringify(field)+"</span></br>");
});
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>
Here I have a sample answer which appends all list of country. Understand each and every line and function how it works. I have appended list of country, how to render the rest items that I leave it to you. Don't get discouraged or disappointed; learning to code is a journey, not destination.
Note:https://cors-anywhere.herokuapp.com/ is added if you are running it in your localhost to avoid CORS's problem. If you have hosted the page, you can remove it.
$(document).ready(function(){
$("button").on('click',function(){
$.getJSON("https://cors-anywhere.herokuapp.com/https://api.covid19api.com/summary", function(result){
var obj=result;
var json = JSON.stringify(obj);
var s = JSON.parse(json);
s.Countries.map(function(c){
$("#result").append("<span>"+c.Country+"</span></br>");
})
console.log(s.Countries[0].Country);
});
});
});

Not displaying the table in web page using flask

Hi I am using flask to create a web app in python.
In my profile.html page in template direcotiry I have profile.html as shown below.
<!DOCTYPE html>
<html lang="en">
<head>
<title>App</title>
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
<script src="../static/js/jquery-1.11.2.js"></script>
<script src="../static/js/getAcademic.js"></script>
</head>
<body>
<div class="jumbotron">
</div>
</body>
</html>
In the app.py,
#app.route('/getDetails')
def getDetails():
try:
#get data from mysql database and convert to a json and return
return json.dumps(academic_dict)
except Exception as e:
return render_template('error.html', error=str(e))
The returned json object is as follows,
In my js file,
$(function() {
$.ajax({
url: '/getDetails',
type: 'GET',
success: function(res) {
var div = $('<table>')
.attr('class', 'list-group')
.append($('<tr>')
.attr('class', 'list-group-item active')
.append($('<td>')
.attr('class', 'list-group-item-text'),
$('<td>')
.attr('class', 'list-group-item-text')));
var wishObj = JSON.parse(res);
var wish = '';
$.each(wishObj,function(index, value){
wish = $(table).clone();
$(wish).find('td').text(value.Title);
$(wish).find('td').text(value.Data);
$('.jumbotron').append(wish);
});
},
error: function(error) {
console.log(error);
}
});
});
json is converted and returned correctly but the data is not displaying in the profile.html page. I checked the console and it is displaying the error Uncaught ReferenceError: table is not defined in the .js file.
I want to display a table with the data returned as the json object but the table is not displaying when the profile.html page is loading. Please help me with this.
You've got one simple mistake (but don't worry, that happens to everyone...) on the line wish = $(table).clone(); – you use table to reference <table> you saved in variable div .
Either replace $(table) with $(div) there or (I would suggest this solution for readability) rename var div = $('<table>') in the beginning to var table = ...
(Sorry for reviving such an old post, but I'm on badge hunt :])
Oh, and one more point: please don't use screenshots of code, but the code itself (even just shortened) for us to test your problem and our solution:
[{'Title': 'Name', 'Data': 'john mark'},
{'Title': 'Faculty', 'Data': 'cs'}]`

Reading JSON from <script> Tag

How can I get JSON data embedded in a script tag?
<!DOCTYPE html>
<html>
<head>
<script id="data" type="application/json">{org: 10, items:['one','two']}</script>
<script type="text/javascript">
var obj = JSON.parse( document.getElementById('data').value );
console.log( obj );
console.log( obj.org );
</script>
</head>
<body>
</body>
</html>
I'm getting:
Uncaught SyntaxError: Unexpected token u in JSON at position 0
<script> elements are not form controls. They don't have value properties (so. when you read it, you get undefined which is "undefined" when cast to a string, and that isn't valid JSON).
Read the content of the text node inside the element instead.
You also need to write JSON instead of a JavaScript object literal.
Property names must be strings, not identifiers.
Strings must be quoted with " not '.
<script id="data" type="application/json">{"org": 10, "items":["one","two"]}</script>
<script type="text/javascript">
var obj = JSON.parse(document.getElementById('data').firstChild.data);
console.log(obj);
console.log(obj.org);
</script>
The u comes from "undefined". Try:
JSON.parse( document.getElementById('data').innerHTML );
...but keep in mind that your current input is not JSON. So correctly formatted it would be:
<script id="data" type="application/json">{"org":10,"items":["one","two"]}</script>

JSON Data and Manipulating the Content

I am trying to write out the data from this JSON url into li's.
The JSON link is https://www.inquicker.com/facility/americas-family-doctors.json
<!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>
You can add a test to check if the length of available_times array is > 0 before accessing the first cell.
And then, you can access to when or url properties :
available_times[0].when
available_times[0].url
Edit : save name.available_times[0] in a temp var and write
temp.when or temp.url.
I have created a JSFidle check this. You to check the data is available in available_times then proceed.
if (name.available_times.length){.......
.....
....
$(document).ready(function(){
$.getJSON('https://www.inquicker.com/facility/americas-family-doctors.json',
function(data){
$.each(data.schedules, function(i, name){
times=''
if (name.available_times.length){
times='<ul>'
times+='<li>'+name.available_times[0].when+'</li>'
times+='</ul>'
}
else{
times='<ul><li>No Time Available</li></ul>'
}
$('#names').append('<li>' + (name.name) + times + '</li>');
});
});
});
In the JSON link, some schedules have empty available_times arrays.
And available_times[0] is an object that contains the properties when and url, so you'll have to write name.available_times[0].url

Problem when reading from JSON file using javascript

<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript" src="js/jquery-1.3.2-vsdoc.js"></script>
<script type="text/javascript">
$(function() {
$("#Button1").click(function() {
$.getJSON("ticketPriceInArray.js",
function(json) {
var ticketPriceArray=[json.tickets[0].price, json.tickets[1].price,
json.tickets[2].price, json.tickets[3].price, json.tickets[4].price,
json.tickets[5].price];
alert(json.tickets[0].type);
var inputWord =$("#keyword").val();
if (inputWord=="A"){$("#result").text(ticketPriceArray[0]);}
if (inputWord=="B"){$("#result").text(ticketPriceArray[1]);}
if (inputWord=="C"){$("#result").text(ticketPriceArray[2]);}
if (inputWord=="D"){$("#result").text(ticketPriceArray[3]);}
if (inputWord=="E"){$("#result").text(ticketPriceArray[4]);}
if (inputWord=="F"){$("#result").text(ticketPriceArray[5]);}
});
});
});
</script>
Here is "ticketPriceInArray.js"
{
"tickets":[
{
"type":"A Ticket",
"price":220,
},
{
"type":"B Ticket",
"price":180,
},
{
"type":"C Ticket",
"price":120,
},
{
"type":"D Ticket",
"price":100,
},
{
"type":"E Ticket",
"price":80,
},
{
"type":"F Ticket",
"price":50,
}
]
}
This is a simple html where when the corresponding text inputed, the corresponding ticket price will show in the html after a button-click. All the ticket info is stored in a .json file named "ticketPriceInArray.js" and I have been trying to read it using $.getJSON(), but unfortunately I haven't been able to get any success. The weird thing is I didn't get any warning on anything so I couldn't fix it. Please see if you can give me any suggestions. Thank you.
By adding an AJAX error handler, I received this
"parsererror" SyntaxError: Unexpected token }
The problem is the trailing commas after each price property.
The following example is working fine in FF and Chrome with the exact JSON you provided. In IE you will have to remove the commas after the prices, as Phil already said.
In my test both the test.html and test.js were placed in my apache server root; viewing the files directly from my desktop into my browser didn't work apparently due to security restrictions.
<html>
<head></head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/javascript">
$(function() {
$("#Button1").click(function() {
$.getJSON("test.js", function(json) {
for (var i in json.tickets) {
var type = json.tickets[i].type;
var price = json.tickets[i].price;
$('#result').append('<span>type: ' + type+ ', price: ' + price + '</span><br />');
}
});
});
});
</script>
<button id="Button1">click me</button>
<div id="result"></div>
</body>
</html>
I suggest you use http://jsonlint.com/ to validate your JSONs; or just rely on a good encoder instead of doing it by hand ;)
A little bit different approach to solving this problem. This is assuming that you aren't changing your ticket prices based on some data that you pass to the url.
ticketPriceInArray.js
{
"A" : 220,
"B" : 180,
"C" : 120,
"D" : 100,
"E" : 80,
"F" : 50
};
main file
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript" src="js/jquery-1.3.2-vsdoc.js"></script>
<script type="text/javascript">
var ticket_prices = {};
$(function() {
$("#Button1").click(function() {
$.getJSON("ticketPriceInArray.js", function(returnedJSON) {
ticket_prices = returnedJSON;
$("#result").text( ticket_prices[ $("#keyword").val() ] );
});
});
});
</script>
If there are any considerations (or questions about my assumptions) let me know and I will update based on that.
Assuming the following facts:
you're using firefox
there is no traffic in the network-tab when you click on #Button1
there are no errors logged
... I would like to say:
the element you click on is not $("#Button1")
Are you sure that the element you click on has the ID "Button1" and that there is only one element using that ID ?
Are you running this from a webserver or from your local filesystem?

Categories