Passing JSON from HTML to jQuery [duplicate] - javascript

This question already has answers here:
I keep getting "Uncaught SyntaxError: Unexpected token o"
(9 answers)
Closed 7 years ago.
I am having a problem parsing simple JSON strings. I have checked them on JSONLint and it shows that they are valid. But when I try to parse them using either JSON.parse or the jQuery alternative it gives me the error unexpected token o:
<!doctype HTML>
<html>
<head>
</head>
<body>
<script type="text/javascript">
var cur_ques_details ={"ques_id":15,"ques_title":"jlkjlkjlkjljl"};
var ques_list = JSON.parse(cur_ques_details);
document.write(ques_list['ques_title']);
</script>
</body>
</html>
Note: I'm encoding my strings using json_encode() in PHP.

Your data is already an object. No need to parse it. The javascript interpreter has already parsed it for you.
var cur_ques_details ={"ques_id":15,"ques_title":"jlkjlkjlkjljl"};
document.write(cur_ques_details['ques_title']);

Try parse so:
var yourval = jQuery.parseJSON(JSON.stringify(data));

Using JSON.stringify(data);:
$.ajax({
url: ...
success:function(data){
JSON.stringify(data); //to string
alert(data.you_value); //to view you pop up
}
});

The source of your error, however, is that you need to place the full JSON string in quotes. The following will fix your sample:
<!doctype HTML>
<html>
<head>
</head>
<body>
<script type="text/javascript">
var cur_ques_details ='{"ques_id":"15","ques_title":"jlkjlkjlkjljl"}';
var ques_list = JSON.parse(cur_ques_details);
document.write(ques_list['ques_title']);
</script>
</body>
</html>
As the other respondents have mentioned, the object is already parsed into a JS object so you don't need to parse it. To demonstrate how to accomplish the same thing without parsing, you can do the following:
<!doctype HTML>
<html>
<head>
</head>
<body>
<script type="text/javascript">
var cur_ques_details ={"ques_id":"15","ques_title":"jlkjlkjlkjljl"};
document.write(cur_ques_details.ques_title);
</script>
</body>
</html>

cur_ques_details is already a JS object, you don't need to parse it

Response is already parsed, you don't need to parse it again. if you parse it again it will give you "unexpected token o". if you need to get it as string, you could use JSON.stringify()

I had the same problem when I submitted data using jQuery AJAX:
$.ajax({
url:...
success:function(data){
//server response's data is JSON
//I use jQuery's parseJSON method
$.parseJSON(data);//it's ERROR
}
});
If the response is JSON, and you use this method, the data you get is a JavaScript object, but if you use dataType:"text", data is a JSON string. Then the use of $.parseJSON is okay.

I was seeing this unexpected token o error because my (incomplete) code had run previously (live reload!) and set the particular keyed local storage value to [object Object] instead of {}. It wasn't until I changed keys, that things started working as expected. Alternatively, you can follow these instructions to delete the incorrectly set localStorage value.

Related

How to access JSON file in JavaScript?

I have a JSON file as data.json and I have an HTML file with JavaScript embedded in it. I want to access data from the JSON file in a simple HTML(file:///C:/Users/XYZ/Desktop/htmlpage.html) file and NOT in a server-client manner(http://....). I have tried following simple code to import JSON file.
<!DOCTYPE html>
<html>
<body>
<p>Access an array value of a JSON object.</p>
<p id="demo"></p>
<script type="text/javascript" src="F:/Folder/data.json">
var myObj, x;
x = data[0].topic;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
I have read this method of using
<script type="text/javascript" src="F:/Folder/data.json">
on other StackOverflow Questions. But it is not working.
Please tell me the simplest way to access the data in the JSON file.
You could try writing something like this in your JSON file in order to assign the data to a variable:
window.data = JSON.parse('insert your json string here');
You can then access window.data in your page's javascript. You can also omit window. and just assign and/or read from data, which is the same as window.data.
Perhaps a cleaner approach would be to use an AJAX request either with jQuery or vanilla Javascript, both approaches have many answers available on this site.
You could also look into a solution with jQuery.getJSON(): Loading local JSON file
If you are able to use PHP for your desired task (accessing data from JSON file and doing some stuff with data) it will be easier to use PHP to open JSON files. You can use following code to access JSON files.
<?php
$str = file_get_contents('data.json');
$json = json_decode($str, true);
?>
Here $json will be the outermost object (if file starts with '{') / array (if file starts with '['). Then you can use it in a regular way.
Maybe some of you can think that why I'm posting PHP solution in Javascript question? But I found this very much easier than opening file in Javascript. So if you are allowed to use PHP go with that.

Convert JSON object to string without JSON

This is my server response:
{"names":["Kreisler","Kreisler","Kreisler"]} .
If I use the above JSON response in JavaScript, I am getting an 'object' datatype
as [object Object]. Instead of getting Object type, I want to get the JSON response in string format.
Note: I don't have JSON js from my html.so I will not be able to use
JSON.stringify({"names":["Kreisler","Kreisler","Kreisler"]}).
Or let me know how can I install JSON here.
<!DOCTYPE html>
<html>
#<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
ss = {"names":["Kreisler","Kreisler","Kreisler"]}
document.getElementById("demo").innerHTML = ss;
}
</script>
</html>
<!DOCTYPE html>
<html>
#<button type="button" onclick="myFunction()">Try it</button></br>
<div id="demo"></div>
<script>
function myFunction() {
var ss = JSON.stringify({"names":["Kreisler","Kreisler","Kreisler"]});
document.getElementById("demo").innerHTML = ss;
}
</script>
</html>
There are several possible ways to solve your problem. The first is simply to examine how you are making your request to the server. Chances are that you can stop parsing the response to JSON and instead keep it a string.
If you don't have any control over that portion of the code, you will have to stringify the JSON object. You say that you don't have JSON.stringify available in the browser which is suspicious. window.JSON is a global and doesn't need to be "installed" at all. According to the MDN, window.JSON was available all the way back to IE 8:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON
If you're using a custom browser implementation, the first option is probably your best.

Posting JSON data using jquery gives me empty variable [duplicate]

This question already has answers here:
Reading JSON POST using PHP
(3 answers)
Closed 6 years ago.
I have this html / javascript :
<html>
<head>
</head>
<body>
<script src="view/backoffice/assets/plugins/jquery/jquery-1.11.1.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
var data = {'user_id':'2680',
'ship_to_name':'John Doe',
'ship_to_address':'Somewhere in Jawa Timur',
'ship_to_city':'Surabaya',
'ship_to_area':'Wonocolo',
'ship_to_phone':'080000000'};
$.ajax({
url: "../controller/ctrl.php",
type: 'POST',
contentType:'application/json',
data: JSON.stringify(data),
dataType:'json'
});
});
</script>
</body>
</html>
and I have this PHP on my server :
<?php
$jsonReceiveData = json_encode($_POST);
file_put_contents('storedvar.php', $jsonReceiveData);
?>
but what I got in storedvar.php is just empty variable of json. just like this [].
why I can't get json sent data? thank you.
your data is json , not a string.
replace it like this but dont split the lines.
var data = "{'user_id':'2680',"+
"'ship_to_name':'John Doe',"+
"'ship_to_address':'Somewhere in Jawa Timur',"+
"'ship_to_city':'Surabaya',"+
"'ship_to_area':'Wonocolo',"+
"'ship_to_phone':'080000000'}";
if that works you might wish to remove the stringify and see if the original json works.

Simple jQuery script fails to do anything

I'm new to jQuery and I have a simple jQuery script.
I've put this in my header:
<script src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'/>
In my body, I have this:
<script type='text/javascript'>
$(document).ready(function() {
alert(1);
$.getJSON('http://puppygifs.tumblr.com/api/read/json', function(data) {
alert(2);
});
});
</script>
But, while Firebug says the JSON is accessed and there are no errors, I only get the first alert, not the second. Why doesn't the second alert execute?
The json response returned by http://puppygifs.tumblr.com/api/read/json is not valid json, which causes the success handler not to execute.
If you look at the first line the response its var tumblr_api_read={, which isn't valid. To see a valid json example checkout: http://json.org/example.html
This situation is noted in the Jquery Documentation:
As of jQuery 1.4, if the JSON file contains a syntax error, the
request will usually fail silently. Avoid frequent hand-editing of
JSON data for this reason. JSON is a data-interchange format with
syntax rules that are stricter than those of JavaScript's object
literal notation. For example, all strings represented in JSON,
whether they are properties or values, must be enclosed in
double-quotes. For details on the JSON format, see http://json.org/.
getJson Documentation
Also be sure to close the script tag with an end tag and not the shorthand end tag
<script src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'></script>
If you are accessing this json from outside the providing domain you must indicate its jsonp This can be accomplished by appending &callback=? to the url as described in the jQuery Documentation.
$(document).ready(function() {
alert(1);
$.getJSON('http://services.faa.gov/airport/status/SFO?' +
'format=application/json&callback=?', function(data){
alert(2);
});
});
JS Fiddle http://jsfiddle.net/J5jYW/

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

Categories

Resources