How to handle my JSON data in jQuery Ajax success callback? - javascript

If I have a ajax call:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(json_data){
//What's the efficient way to extract the JSON data and get the value
}
});
Server returned to my js the following JSON data
{"contact":[{"address":[{"city":"Shanghai","street":"Long
Hua Street"},{"city":"Shanghai","street":"Dong Quan
Street"}],"id":"huangyim","name":"Huang Yi Ming"}]}
In my jQuery AJAX success callback function, how to extract the value of "name", value of "address" (which is a list of object) elegantly?
I am not experienced with jQuery and JSON data handling in javascript. So, I would like to ask some suggestions on how to handle this data efficiently. Thanks.

A JSON string gets parsed into a JavaScript object/array. So you can access the values like you access any object property, array element:
var name = json_data.contact[0].name;
var addresses = json_data.contact[0].address;
Do access the values inside each address, you can iterate over the array:
for(var i = addresses.length; i--;) {
var address = addresses[i];
// address.city
// address.street
// etc
}
If you have not so much experience with JavaScript, I suggest to read this guide.

Related

How to tell JavaScript that my variable is an array and not a string?

I'm using flask and my backend returns to AJAX a response in the form of a python list, and then JavaScript understands it as a string, but that's a problem because I have to iterate over that list.
All i could find on the internet is how to check the type of a variable, but couldn't find any method (which in python is pretty straightforward) to change it
The Array.isArray() method determines whether the passed value is an Array or not.
var someNumbers = [1,2,3];
console.log( Array.isArray( someNumbers ) );
and if it is an array it will return
true
Check this link to know more about Array.isArray
If your response is a string, you can use JSON.parse to turn it into an JS Object/Array.
var response = someAjaxStuff(...);
// response is a string
response = JSON.parse(response);
// now reponse is an Object/Array
If you use AJAX with jQuery, you can also use dataType:
$.ajax({
url: 'https://example.com/api/somejson',
dataType: 'json',
method: 'get',
success: function(res) {
// console.log res will be an object/array here.
}
});
But if you're writing your own API, I suggest you have to add the right header to tell browser that it is a JSON format instead of string.
For flask you can use jsonify (reference):
return jsonify(somedict)

Using JSONP and I have 'ReferenceError: data not defined'

I've got a problem with displaying JSON data called via JSONP. I've got a complex JSON file delivered cross domain via a URL and I'm quite the novice at JSON and ajax. I followed a JSONP article here at https://learn.jquery.com/ajax/working-with-jsonp/ and that worked a treat. Now I am trying to iterate through the JSON object and display data in the HTML page after following this question How do I iterate through this JSON object in jQuery? and I'm not going anywhere. The data is not defined and I'm not sure what I am doing wrong:
// Using LibCal and JSONP
$.ajax({
url: "https://api2.libcal.com/1.0/room_bookings_nickname/?iid=3356&group_id=12306&key=92a47e5c854dee620cca071648c3fc41",
// The name of the callback parameter, as specified by the YQL service
jsonp: "callback",
// Tell jQuery we're expecting JSONP
dataType: "jsonp",
// Tell LibCal what we want and that we want JSON
data: {
q: "select Room name,booked timeslots,booking name from LibCal room bookings",
format: "json"
},
// Work with the response
success: function( response ) {
console.log( response ); // server response
}
});
$.each(data.bookings, function(index, element) {
alert(element.timeslots.room_name);
});
I hope it's an obvious fix to a more advanced user our there :)
Thats because your data object doesn't exist. The data key you're referring to is a on the object you're passing to the $.ajax method.
You need to execute your function inside the success callback in order for it make any sense.
$.ajax({
...
// keep all your original stuff
...
success: function( response ) {
var data = response;
$.each(data.bookings, function(index, element) {
alert(element.timeslots.room_name);
});
}
});
I did the request like this. You need to go one level more to access the array to loop.
var json_url = "https://api2.libcal.com/1.0/room_bookings_nickname/?iid=3356&group_id=12306&key=92a47e5c854dee620cca071648c3fc41"
$.ajax({
url: json_url,
crossDomain:true,
dataType:"jsonp"
}).done(function(response) {
// at the end of request
//Yours --->response.bookings
//Mine --->response.bookings.timeslots
//access the array to loop
var rooms = response.bookings.timeslots;
$.each(rooms, function(index, element) {
create_elem(element.room_name, index);
});
});
Here is a working version in jsFiddle - https://jsfiddle.net/9e746pkh/
Hope this helps.

Loading JSON from Dojo JsonRest into object variable

According to this post Remove String from JSON, I want to fill a Dojo Selectbox with JSON Data. The Problem is that I have to change the JSON Data before I can handout the data to the dijit.form.select Box.
I get the data via JsonRest. The question if, how I can load the Json Data into a normal object variable? I tried this here but it did not work.
var processStore = new JsonRest({
target: "http://cnwin.ebusiness.local/activiti-rest/service/repository/process-definitions?startableByUser=kermit",
headers: {"Authorization": "Basic a2VybWl0Omtlcm1pdA=="},
allowNoTrailingSlash: false
});
var processes = processStore.query("",{});
I simply want to load the JSON data from the JsonRest store in a normal variable.
Thank you
The JsonRest store only accepts an array, so you're not able to retrieve the data, because your store is not able to read that data for you.
If you're only interested in reading the data (so no updating/creating/deleting has to be done), the easiest way is to retrieve that data using an AJAX request and manually put it inside a dojo/store/Memory store, for example:
require([ "dojo/request/xhr", "dojo/store/Memory" ], function(xhr) {
var url = "http://cnwin.ebusiness.local/activiti-rest/service/repository/process-definitions?startableByUser=kermit";
xhr(url, {
handleAs: json
}).then(function(data) {
if (data.data !== undefined) {
var myStore = new Memory({
data: data.data
});
// Do something with "myStore"
});
});
If you're interested in the full capabilities of the JsonRest store, you will have to extend it by yourself. If you look at the code you can see several AJAX requests, in:
get()
put()
remove()
query()
Now you can write your own store and extend those methods.

Read json object

I'm having a problem reading JSON; my PHP server encodes an object created with the stdClass, then sends this object on my Ajax asynchronous script. I tried to alert the object and the
representation is like this:
alert(prova) //Gives {"idProva":"3","name":"test"}
Now if the variable name is prova, how can I read the value 3?
I tried using prova.idProva, but it doesn't work.
try parsing json into a object
var json = '{"idProva":"3","name":"test"}',
obj = JSON.parse(json);
alert(obj.idProva);
i hope this will help
In ajax all add dataType:'json'
$.ajax({url: '',
dataType: 'json',
type: 'GET',
success: function (prova) {
alert(prova.idProva);
}
);
This may help you,
var data = {"idProva":"3","name":"test"}
console.log(data['idProva']);

Building a json tree structure

I will be passing a json string to a servlet via an ajax request :
function add() {
$.ajax({
url: "pathToServlet" ,
dataType: "text",
data: ({
name : 'myJsonString'
}),
success: function(data) {
alert('returned!!');
});
}
To build up this json string I have a listener which when fired appends a new piece of json to string :
var json = "";
json += "{ new json ..... }"
Is this the correct way to build up the jSon String ? Should I be using jQuery methods to create a json object(if they exist) and add elements to it and then convert the json object to a string instead of creating the json string myself ?
What I would recommend doing is building up an object, and then when you're ready to send it to the server, serialize the object via JSON.stringify.
So for instance, you might have an object called data:
var data = {};
...to which you might periodically add properties:
data.foo = "bar";
data.stuff = {nifty: "stuff"};
Or perhaps data is an array:
var data = [];
...to which you add things:
data.push({nifty: "stuff"});
Then, when you're ready to send it:
function add() {
$.ajax({
url: "<%=savePortlet%>" ,
dataType: "text",
data: {
name : JSON.stringify(data)
},
success: function(data) {
alert('returned!!');
});
}
Because you're passing an object into ajax, you don't have to worry about URL-encoding the JSON string; jQuery will do it for you.
JSON.stringify is defined as part of ECMAScript5 and suppoted natively by many browsers, but of course many of us have to support outdated versions of browsers. In those cases, you can get a "JSON shim" to add JSON.stringify to an environment that doesn't have it. One of those is available from the originator of JSON, Douglas Crockford, on his github page.
If using jQuery you can use jquery-json, a really handy plugin to handle JSON with JavaScript and jQuery.
Usage:
var jsonString = $.toJSON(myObject);

Categories