Reputation: 787
AJAX call as follows:
$.get('file.php')
.done(function(data) {
console.log(data);
});
Console returns:
[{"0":"PS001","code":"PS001"}]
However if amend the log to console.log(data.code)
it returns undefined
. Also, traversing JSON using each
as such:
.done(function, data) {
$.each(data, function(key, value) {
console.log(value.code);
});
)};
results in the following error:
[Error] TypeError: [{"0":"PS001","code":"PS001"}] is not a valid argument for
'in' (evaluating 'b-1 in a')
JSON looks well-formed, so not sure what the issue is?
Upvotes: 0
Views: 814
Reputation: 3015
JSON_ENCODE
returns string.
Learn more about JSON_ENCODE
You should convert that JsonArrayString to JsonArray
$.get('file.php')
.done(function(data) {
var arrayObj = JSON.parse(data);
$.each(arrayObj , function(key, value) {
console.log(value.code);
});
});
Upvotes: 2
Reputation: 18600
Try this, because your code return json array.
console.log(data[0].code); //If you getting JSON format
OR
console.log(JSON.parse(data)[0].code); //If you getting JSON as String
Upvotes: 1
Reputation: 31739
It is a json
string. You need to parse it first. Try with -
data = $.parseJSON(data);
$.each(data, function(key, value) {
console.log(value.code);
});
Upvotes: 1
Reputation: 5899
Try this:
$.get('file.php')
.done(function(data) {
var json = JSON.parse(data)[0];
console.log(json .code);
});
Upvotes: 1