Convert JSON object to string without JSON - javascript

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.

Related

Passing JSON from HTML to jQuery [duplicate]

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.

How to get the result in JSON format from google?

I have tried to query google using my script but my request is going to Google.com page.
What I am looking for is how I can request google for result and out the result on my test html in json format. Here is what I tried:
<html>
<body>
<script type="text/javascript">
function google()
{
var str=document.getElementById('googlebox').value;
str="http://www.google.com/search?hl=en&source=hp&q=" + str + "&aq=f&oq=&aqi=";
var replaced=str.replace(" ","+");
window.location.replace(replaced)
}
</script>
<input type="text" value="Google" id="googlebox"/>
<input type="button" value="Go" onclick="google()"/>
</body>
</html>
You can't.
For any given a URL, a server returns what it returns.
You can't make a server return data in an arbitrary format (or force it to use CORS to grant permission to your script to read that data).
You should look into google's custom search API. It has an option to return data in JSON format.
https://developers.google.com/custom-search/json-api/v1/using_rest

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

Reaching a data in json using getJSON

I want to get the username's profile image. So i prefer to use twitter api version 1 for this.(The regular version of api is here). But my code doesn't return any data. How can i fix this?
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script>
$(document).ready( function() {
var userPage = "https//twitter.com/jack";
var arr = userPage.split("/");
var username = "";
for(i=3;i<4;i++)
username += arr[i];
var page = 'https://api.twitter.com/1/users/show.json?screen_name='+username;
$.getJSON(page, function(data) {
alert(data.profile_image_url);
});
})
</script>
</head>
<body>
</body>
</html>
Add "&callback=?" to the URL to force jsonp format to get around the Access-Control-Allow-Origin issue.
var page = 'https://api.twitter.com/1/users/show.json?screen_name='+username + "&callback=?";
EXAMPLE
JSONP:
The way JSONP works is simple, but requires a little bit of
server-side cooperation. Basically, the idea is that you let the
client decide on a small chunk of arbitrary text to prepend to the
JSON document, and you wrap it in parentheses to create a valid
JavaScript document (and possibly a valid function call).
The client decides on the arbitrary prepended text by using a query
argument named jsonp with the text to prepend. Simple! With an empty
jsonp argument, the result document is simply JSON wrapped in
parentheses.

why JavaScript is not displaying parsed json data?

This is format of JSON data: [{"options":"smart_exp"},{"options":"user_int"},{"options":"blahblah"}] that I receive through getjson from server. I need to append json with user input. I am trying to do it in this way: 1st convert it into javascript object, append it with user input, again convert to json object & send it back to server for database update. I have converted json to javaScript object using eval(). Now not able to manipulate javascript object. If I convert javascript object back to json object, it displays correctly all data that was sent from server.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html><head></head>
<body>
<form name="index">
<p><input type = "text" id = "txt" name = "txt"></input></p>
<p><input type = "button" id = "send" name = "send" value = "send"
onClick="ADDLISTITEM();"></input></p>
<select name="user_spec" id="user_spec" />
</form>
<script>
function ADDLISTITEM()
{// this script suffers from errors on eval/JSON.parse methods
alert (json.length);//outputs corrcet with eval
tring = JSON.stringify(json);//outputs corrcet with eval
alert(jsonString);//outputs corrcet with eval
alert(json.options[0]);//no output
}
</script>
<script src="http://code.jquery.com/jquery-latest.min.js">
</script>
<script src="http://www.json.org/json2.js"></script>
<script>
var json;
$(document).ready(function() {
jQuery .getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
json = eval(jsonData);
//json = JSON.parse(jsonData);/*error if uncomment:"IMPORTANT: Remove this line from
json2.js before deployment"*/
$.each(jsonData, function (i, j) {
document.index.user_spec.options[i] = new Option(j.options);
});});
});
</script>
</body>
</html>
In jQuery, $.getJSON()'s callback gets called with parsed JSON data; just use it.
$.getJSON("*.php", function(data) {
$.each(data, function() { alert(this.options); });
);
should give you an alert for every {"options": "xyzzy"} object in the array.
EDIT after OP edited their post:
Your edit clarifies things a little: You won't get any data back -- and it will be completely silent, too, as I found out -- if you violate the same origin policy.
Basically (with exceptions (preflight checks, etc)), you can only access URLs on the exact same domain via AJAX. If your HTML file is a static file served locally, it can not access http://127.0.0.1/; if your file is http://foo.baz.quux.org/, you can't simply AJAX into http://mordor.baz.quux.org .
I don't think the problem here has anything to do with eval/parse etc or the same origin policy. Your json is an array of objects each containing a member named options. Therefore you cannot do json.options[0], you have to do json[0].options.
var json = [{"options":"smart_exp"}, {"options":"user_int"}, {"options":"blahblah"}]
for (var i = 0; i < json.length; i++){
alert(json[i].options)
}

Categories

Resources