10

I am starting work on a project that is built completely on JSON data. It is returned like this:

{"location":{"id":10,"contactPhone":"8675309","contactName":"bob","name":"bill smith","zipCode":"90210","state":"California","address1":"104 S. Olive","city":"Temecula","country":"USA"},"success":true}

I am comfortable processing data returned in HTML form (usually tables) by traversing the DOM with the .find and other filtering to find success flags. I have no idea how to do this with JSON - I need to filter to the last object "success" and check if it is true or false. With HTML returned data I do it like this:

submitHandler: function(form) {
    $.ajax({
     //other ajax stuff
      success: function(data) {
        var answer = $(data).find("td:eq(1)").text();
        var message = $(data).find("td:eq(3)").text();
        //console.log(data);
        if (answer == "True") {
          $('#messages').show().html(message);
      } else {
          $('#messages').show().html('Error logging in: ' + message);
      }
    }
  });
  return false;
  }
  1. Even after using this method I don't completely understand what the function(data) means, Ive used data, msg and response without really understanding what the difference between them are.

I am able to post to the webservice and get the returned JSON with this .ajax call

$.fn.serializeObject = function() {....}
submitHandler: function(form){
    var wrapper = {};
    var location = {};
    wrapper.location = $("#newLocation").serializeObject();
        $.ajax({
            type: $(form).attr('method'),
            url: '/web/service/' + 'locationService' + '/' + 'createLocation',
            dataType: 'json',
            async: false,
            data: JSON.stringify(wrapper),
            success: function(msg) {
                    console.log('success' + msg );
                    //need to traverse to success and if true, do something
            },
                    error: function(msg) {
                    console.log('failure' + msg );
                    //need to traverse to success and if false, do something
            }
    });
    return false;
}
  1. How do you filter to the "success" part in a JSON string (string or object?)
  2. What are the correct terms for the key/number pairs in the JSON string i.e. "contactPhone":"8675309"?
  3. How do you then display the data if "success":"true"? I would imagine you just appendTo a table somehow?
halfer
  • 19,824
  • 17
  • 99
  • 186
Dirty Bird Design
  • 5,333
  • 13
  • 64
  • 121

2 Answers2

4

msg here is a json formatted object. You can get success value like that:

success: function(msg) {
                    console.log('success' + msg.success );
                    if(msg.success) { //could be wrote: msg.success === true
                        //do some stuff
                    }
            },

"contactPhone":"8675309"

contactPhone is the key, "8675309" is the value. But in your sample, to get "contactPhone" value, you need to first get the location object:

var contactPhoneValue = msg.location.contactPhone;
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • So is it just looking for the word "success" in the msg? How do you differentiate between "success":"true" and "success":"false"? Also, thank you for clarifying the difference between key/value. I think this will help later when parsing the data and displaying as a table, to somehow ignore the "key" and only display the "value" – Dirty Bird Design May 29 '13 at 19:08
  • 1
    if(msg.success) if true, if(!msg.success) if false – A. Wolff May 29 '13 at 19:09
  • Is it anywhere near correct to assume you would store a var for each key/value as your example var contactPhoneValue = msg.location.contactPhone; and the do something like (shit don't know how - would be an .each function?) contactPhoneValue ? – Dirty Bird Design May 29 '13 at 19:22
3

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. http://www.json.org/

Now the code for reading and writing properties of json object is very similar as it is for normal javascript object.

$ajax({
  dataType:'json',
  success:function(data){
        console.log(data['success']);   //returns for whatever will be the value for succes
        //or
        console.log(data.success);   //returns for whatever will be the value for succes
        data.location['contactName'] = "new name";                    
 }
});

Accessing and manipulating javascript and Json object is same.
Here is a very good guide for them:
http://www.dyn-web.com/tutorials/obj_lit.php



UPDATED:
A better version, maybe this could help:
http://jsfiddle.net/hvzcg/4/

TaLha Khan
  • 2,413
  • 2
  • 25
  • 39
  • Thank you, hopefully this will make more sense after reading from the links you provided. I am still not making the connection on how to parse the string and display the values in a table – Dirty Bird Design May 29 '13 at 19:17
  • would you just do the same data['contactName'] = "new name"; for each key/value pair? If so how would you display the result? – Dirty Bird Design May 29 '13 at 19:47
  • Yes you can do this for any value in the json object, i updated the answer its data.location.['contactPhone'] not data['contactPhone'] – TaLha Khan May 29 '13 at 19:54
  • 1
    it is: data.location['contactName'] or data.location.contactName You have an extra dot in your sample – A. Wolff May 29 '13 at 20:02
  • mybad , yeah its data.location['contactName']...thanks for correction. – TaLha Khan May 29 '13 at 20:04