0

I would like to deal with differnet JSON-Formats.

In my first example I'am using this answering-format from PHP:

{
    "errors": [ "username", "password" ]
}
$.ajax({
    type: "GET",
    url: "http://www.sample.com/js/l.php",
    success: function(response) {
        console.log(response);
        var jsonResponse = JSON.parse(response);
        if (jsonResponse['errors']) {
            var t = "";
            for (var i = 0; i < jsonResponse['errors'].length; i++) {    
                //works well for: {"errors":["username","password"]} ';
                t = t + jsonResponse['errors'][i] + "  ";
            }
            console.log(t);
        }
    }
});

The result of console is: username password

If I change the json-response to

{
    "errors": { 
        "username": ["credentials"],
        "password": ["credentials"]
    }
}

I do not know how do deal with this.

The function do not work because the jsonResponse['errors'].length is empty.

I would like to loop to username password with their values.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
hamburger
  • 1,339
  • 4
  • 20
  • 41
  • 2
    This is an array. Instead of `errors.username` you use `errors.username[0]` (for the first value). You can loop through unknown keys by using `for (var key in obj) { console.log(obj[key]); }`. – h2ooooooo Dec 18 '14 at 13:04

1 Answers1

1

In your first example, errors is an array, containing two values.

Object: {array: [element1, element2]}

In your second example, errors is an object, and objects don't have a length property.

Object: {Object: {array: [element], array[element]}}

To count the number of elements in an object, you have to iterate over the elements and count them. See the question below to see how:

How do I count a JavaScript object's attributes?

Community
  • 1
  • 1
Jørgen R
  • 10,568
  • 7
  • 42
  • 59
  • If I do: for (var k in jsonErrors) {t = t + jsonErrors[k] +" ";} console.log(t); I will get object object not the values. – hamburger Dec 18 '14 at 13:14