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?

5 Answers 5

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

$.each(arrofobject, function(index, val) {
    console.log(val.category);
});
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

I use this example with jQuery.ajax() and it's working too. Thanks.
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.

3 Comments

OP never said it is an AJAX call :P
@Vega Very true, though if it isn't an ajax call, maybe it doesn't need to be json!
haha true.. was just kidding tho. Most likely, It should be an return from AJAX.
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()

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.