Is there a standard way to serialize JSON using JavaScript and JQuery? - javascript

I've been looking through Stackoverflow for answers and there seems to be more than one way of serializing (converting the JSON response back into HTML and/or other code so we may do something useful with it).
The way I am using is this..
$.getJSON(
"https://www.googleapis.com/shopping/search/v1/public/products?callback=?",
{
key: "unique key code",
country: "US",
q: "iphone",
alt: "json"
},
function(data)
{
$.each(data.items, function(i, item)
{
//Do something with each object
}
}
So I'm using the $.getJSON method to retrieve the JSON response then looping through each object and doing something.
Is this way fine? Should I be using another function to retrieve the JSON response?
Regards,
LS

if you set dataType to json jquery parses json for you
$.ajax({
dataType:"json",
...
success:function(data){
$.each(data.items, function(i, item)
{
//Do something with each object
}
}
});

No, you are doing it perfectly fine. jQuery handles the conversion of "string" to json data and back.
There are native implementations of converting to and from JSON within browsers, however it is important to note that older browsers do not support this out of the box. You should include the json2.js library to ensure JSON support.
var dataJson={"something":"special"};
var jsonString=JSON.stringify(dataJson);
var dataJsonAgain=JSON.parse(jsonString);
jQuery has an additional hack in how it parses JSON if there is no native implementation, without using eval, since eval is evil! It looks somewhat like this;
(new Function("return "+dataJson))()
simplest way would be to stick to jQuery and its parseJSON function that does the polyfill for you.

Related

Using $.get("url",data) again in jQuery?

I'm attempting to use the $.get() function to get data from a page, and then parse the data through jQuery, such as getting all the images, and then putting it into the body of the user's page.
$.get("/character/hats").done(function(data) {
//$("body").prepend(data);
/*data?*/$(".card > .card-body .col-md-4").each(function(){
let hatdata=$(data).find('pull-left').html;
let hatid=0;
$("body").prepend('<p>found!</p><div>'+hatdata+'</div>');
let assetcode=0;
console.log("I see hat id" + "");
});*/
});
Is there a way to use jQuery data response from $.get, and parse it using jQuery again?
To access the data sent back from $.get you merely need to reference it. You shouldn't convert it back to a jQuery object with $().
Here's an example which gets a JSON response.
$.get('https://httpbin.org/get').done(function(data) {
console.log(data); // data is a variable which contains a parsed JSON response to a javascript object.
console.log(data.url);
});
You can view what the response looks like here: https://httpbin.org/get
If the response of your server isnt JSON you will need to do something else.
If the response is HTML you can do it like this:
$.get('https://httpbin.org').done(function(data) {
console.log(data); // data is now a string of html, which you can insert other places
$('.some-div').html(data);
});
$(...) can be used when you want to 'query' the page's DOM with jQuery. You can query a DOM element with regular Javascript, but it won't include lots of helpful methods like .find() or .html(). So basically you convert an element into a jquery element, which is like javascript on steroids, and adds more methods.
The response from $.get however will either be an object (if its JSON) or a string of html (if HTML). You can convert the string of HTML to jQuery, and parse that as well if that's what you want.
$(data).find('.some-element-in-response')
html() is function not a property name
Change:
let hatdata=$(data).find('pull-left').html;
To:
let hatdata=$(data).find('pull-left').html();
Yes you can I did it but in different way. You need change some way and change few ajax setting like following:
$.ajax({
url: "/character/hats",
type: "GET",
dataType: "html",
success: function (data) {
$(".card > .card-body .col-md-4").each(function(){
let hatdata=$(data).find('pull-left').html;
let hatid=0;
$("body").prepend('<p>found!</p><div>'+hatdata+'</div>');
let assetcode=0;
console.log("I see hat id" + "");
}
});

Transforming a json format variable into a javascript array

I am using the Django framework to build a website.
In the Python file (views.py) I send to the Javascript function an array that has been transformed to json data
Python:
json_data=[1,2,3]
return HttpResponse(json.dumps(json_data), mimetype='application/json')
Then, in Javascript I display the json data in the html.
JavaScript:
function get_variable(){
$.get("/xhr_test/json/", function(json_data) {
$('.square').append('<p> ' + json_data + ' </p>');});
};
So far everything works. However, I would like to convert the "json_data", which I believe is a string, into an array.
I tried doing this:
function get_variable(){
$.get("/xhr_test/json/", function(json_data) {
var array = json_data.split(',');
$('.square').append('<p> ' + array[0]+ ' </p>');});
};
Unfortunately, this doesn't work.
Can someone please explain to me what could I do to convert the "json_data" variable into an array in JavaScript?
Thanks a lot.
When you send around data in JSON format it is a string (the main data), but a string formated in such a way that it's easy to recover the data with the original types (ie, your array). Javascript and jquery have different ways to do that. Using jQuery,getJSON is probably the most direct:
http://api.jquery.com/jQuery.getJSON/
You can use your browsers javascript console to see what exactly do your JS variables look like.
"this doesn't work" it's too vague...
Anyway, if I understood your problem, you are dealing with a string, not a JavaScript array... you have to evaluate the data returned from the ajax call:
var theJavaScriptArray = eval('(' + json_data + ')');
or better... use jQuery.ajax and specify json as dataType: jquery doc
In the end, thanks to Zah I discovered the "javascript console", which I didn't know it existed.
I could see that the error was that the "json_data" variable was not a string.
So this is the solution that worked for me:
function get_variable(){
$.get("/xhr_test/json/", function(json_data) {
var b=json_data.toString().split(',');
$('.square').append('<p> ' + b[0] + ' </p>');
});
};
There is a shorthand in jQuery to parse the json string automatically: jQuery.getJSON()
$.getJSON('/xhr_test/json/', function(data) {
console.log(data); // Here data is already a JavaScript object
});
This is basically the same as:
$.ajax({
url: "/xhr_test/json/",
dataType: "json",
success: function(data) {
console.log(data); // Here data is already a JavaScript object
}
});
Which again is about the same as:
$.ajax({
url: "/xhr_test/json/",
success: function(data) {
var json = $.parseJSON(data); // Here data is a string
console.log(data); // And json is JavaScript object
}
});

How to get JSON from PHP to JS?

I have really been searching for almost 2 hours and have yet to find a good example on how to pass JSON data from PHP to JS. I have a JSON encoding script in PHP that echoes out a JSON script that looks more or less like this (pseudocode).
{
"1": [
{"id":"2","type":"1","description":"Foo","options:[
{"opt_id":"1","opt_desc":"Bar"},
{"opt_id":"2","opt_desc":"Lorem"}],
{"id":"3","type":"3","description":"Ipsum","options:[
...
"6":
{"id":"14","type":"1","description":"Test","options:[
...
etc
Problem is, how can I get this data with JavaScript? My goal is to make a .js script that generates a poll based on these JSON datas, but I honest to god can't find any examples on how to do this. Guessing it is some something like:
Obj jsonData = new Object();
jsonData = $.getJson('url',data,function()){
enter code here
}
Any links to any good examples or similar would be highly appreciated. And I thought that encoding the data in PHP was the tricky part...
EDIT:
I got this code snippet to work, so I can review my whole JSON data in JS. But now I can't seem to figure out how to get to the inner data. It does print out the stage number (1-6) but I can't figure out how to get the question data, and then again the options data within each question. Do I have to experiment with nested each loops?
$(document).ready(function()
{
$('#show-results').click(function()
{
$.post('JSAAN.php', function(data)
{
var pushedData = jQuery.parseJSON(data);
$.each(pushedData, function(i, serverData)
{
alert(i);
})
})
})
});
The idea here is to get into the question information in the middle level and print out the qusetion description, then based on the question type - loop through the options (if any) to create checkbox/radiobutton-groups before going on to the next question. The first number represents which stage of the multi stage poll I am currently working on. My plan is to divide it into 6 stages by hiding/showing various divs until the last page where the form is submitted through Ajax.
Not sure but I think, you can use
$.getJSON('url', data, function(jsonData) {
// operate on return data (jsonData)
});
now you can access and operate on the PHP json data,
if you're going to use it outside the getJson call you can assign it to a variable
var neededData;
$.getJSON('url', data, function(jsonData) {
neededData = jsonData;
});
Try the jQuery documentation: http://api.jquery.com/jQuery.getJSON/
This example should get you started:
$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
This example is based on the JSON structure being;
{
"one": "Singular sensation",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}
Do not use echo in PHP. It will print string not JSON.
Use json_encode to pass JSON to javascript.
Use can use each to get the values in JSON at javascript end.
Example
http://www.darian-brown.com/pass-a-php-array-to-javascript-as-json-using-ajax-and-json_encode/
If you are using JQuery there is a really simple solution to your approach as you can see here: http://api.jquery.com/jQuery.getJSON/.
Otherwise I just want you to explain that there is no way to access your JSON directly in JavaScript as you tried in your code above. The main point is, that JavaScript runs on your browser while your PHP script runs on your server. So there must definitely be a communication between them. So you have to request the data from the server over http I would suggest.
HTH

Guidance for retrieving JSON data into Javascript

I have searched here and on Google, but as an inexperienced Javascript hack I'm struggling to find a good example of what I believe is a rather straight forward action.
I have a server-side script that I have coded to provide JSON formatted output (content.php?action=json).
The JSON output is multi-dimensional, ie it is formatted as ...
[Content]
[Class 1]
[Entry 1]
[Entry 2]
[Entry 3]
...
[Class 2]
[Entry 1]
[Entry 2]
...
Both the number of classes and entries are variable.
I am now trying to write a simple Javascript to do the following ...
1) Call my PHP script
2) Copy the returned JSON output into a suitable Javascript array
3) Display parts of this array within my HTML pages
There are a number of "bits" of this puzzle, but I am struggling to put this together. Would anyone put a simple example together for me?
A couple of side questions ...
(i) Does the output file containing the JSON data need to have it's HTML headers altered to indicate it's content type?
(ii) Is jQuery the best approach for this sort of thing?
Thanks in advance.
Pete
jQuery does provide a very easy approach to ajax calls:
$.ajax({
url: '/path-to-php-script',
type: 'get',
dataType: 'json',
success: function(json) {
// gets run after ajax call is successful
// do stuff with json object
// format: json.content.class[0].entry[2]
}
});
Providing dataType: 'json' will automatically eval the response from your php script into a json object.
Here's the jQuery documentation on ajax calls: http://api.jquery.com/jQuery.ajax/
You can control the format of your json data when you create it so you don't need to copy it into an array once you have retrieved it.
$.get("your_php_script.php",
function(data){
// update html with json ( in data )
}, "json");
http://api.jquery.com/jQuery.get/
To answer your side questions
i) the content type for json is application/json
ii) jQuery is the a good ( and popular ) way to retrieve your json as it abstracts away the different methods that browsers will make an ajax request.
(i) the content type can just be plain text. However to be correct, see What is the correct JSON content type?
(ii) jQuery will make fetching and parsing the JSON very easy, although there are other libraries that do this as well. Many people advocate jQuery due to its usability, though.
Now to answer your main question, using jQuery:
$.getJSON('content.php?action=json', function(data) {
// data returns the result of the request, and will be the array
});
See http://api.jquery.com/jQuery.getJSON/

Problem accessing the json data

I am using jquery 1.5. I am using getJSON method to get the json output..
$.getJSON('/products/list/', function(data) { ..... });
The json is structured like..
{"books":["title_of_books1","title_of_books2","title_of_books3"],
"discs":["title_of_discs1","title_of_discs2"],
etc....,
}
Is there a way to convert this into an array using jquery. So I can access it like books[0]
I appreciate any help.
Thanks.
Assuming your JSON syntax is correct, the data would be automatically converted to a native object by jQuery, so inside function (data) { ..... }, you would refer to data.books[0]:
$.getJSON('/products/list/', function(data) {
alert(data.books[0]);
});
use the parseJSON api of jquery.. http://api.jquery.com/jQuery.parseJSON/

Categories