Reputation: 45
I have a JSON Object like below :
var data = "{'key1' : 'value1', 'key2' : 'value2'}";
As it is in JSON format, no parsing required, so I just want to iterate the object using $.each as below:
$.each(data, function(index, value) {
alert(index + ": " + value);
});
It is throwing a console error
Uncaught TypeError: Cannot use 'in' operator to search for '37' in {'key1' : 'value1', 'key2' : 'value2'}(…)
I don't have any idea of what's going wrong. What is it?
Upvotes: 1
Views: 1628
Reputation: 6803
Use this code:
$.each(JSON.parse(data), function(index, value) {
alert(index + ": " + value);
});
Upvotes: 0
Reputation: 181
You just need to change the way value assigned to data variable to something like below:
var data = {key1 : 'value1', key2 : 'value2'};
in place of
var data = "{'key1' : 'value1', 'key2' : 'value2'}";
Upvotes: 3
Reputation: 230
It is not a valid json. so that it throws error.
$(document).ready(function() {
var data = {};
data.key1 = "value1";
data.key2 = "value2";
$.each(data, function(index, value) {
alert(index + ": " + value);
});
});
Demo : https://jsfiddle.net/0d7st5q7/
Upvotes: 1