10

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?

Pratik Gadoya
  • 1,420
  • 1
  • 16
  • 27
Sadu
  • 125
  • 1
  • 1
  • 6

5 Answers5

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

$.each(arrofobject, function(index, val) {
    console.log(val.category);
});
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
8

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
Sonny Chivas
  • 17
  • 10
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
4

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.

Kevin B
  • 94,570
  • 16
  • 163
  • 180
0

var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];
var data = arrofobject.map(arrofobject => arrofobject);
console.log(data)

for more details please look at jQuery.map()

Parth Raval
  • 4,097
  • 3
  • 23
  • 36
0

I was having similar problem and

var dataObj = JSON.parse(data);

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

This solved my problem. Thanks Selvakumar Arumugam

Tanvir Rajeev
  • 13
  • 1
  • 6