How to print jquery object/array

147,344

Solution 1

var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];

$.each(arrofobject, function(index, val) {
    console.log(val.category);
});

Solution 2

What you have from the server is a string like below:

var data = '[{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}]';

Then you can use JSON.parse function to change it to an object. Then you access the category like below:

var dataObj = JSON.parse(data);

console.log(dataObj[0].category); //will return Damskie
console.log(dataObj[1].category); //will return Męskie

Solution 3

Your result is currently in string format, you need to parse it as json.

var obj = $.parseJSON(result);
alert(obj[0].category);

Additionally, if you set the dataType of the ajax call you are making to json, you can skip the $.parseJSON() step.

Share:
147,344
Sadu
Author by

Sadu

Updated on July 09, 2022

Comments

  • Sadu
    Sadu almost 2 years

    I get id and category name from mysql database.

    When I am alerting a result, I get:

    [{"id":"197","category":"Damskie"},"id":"198","category":"M\u0119skie"}]
    

    (Is this object?)

    1. How can I print a result like this:

      Damskie

      M\u0119skie

    2. M\u0119ski - has bad encoding. It should be Męskie. How can I change this?

  • Selvakumar Arumugam
    Selvakumar Arumugam about 12 years
    OP never said it is an AJAX call :P
  • Kevin B
    Kevin B about 12 years
    @Vega Very true, though if it isn't an ajax call, maybe it doesn't need to be json!
  • Selvakumar Arumugam
    Selvakumar Arumugam about 12 years
    haha true.. was just kidding tho. Most likely, It should be an return from AJAX.
  • Sadu
    Sadu about 12 years
    I use this example with jQuery.ajax() and it's working too. Thanks.