Reputation:
i have a simple json which i want to parse it with jquery.here is my code i am using parseJSON but it do not work in jquery
var json = '['+{"lead_req_id":"","listing_id_1_ref":"RH-R-17","listing_id_1":"17"}+']';
when i alert json it give me [object][Object]
var getReq = jQuery.parseJSON(json);//i tried json[0] also but no luck
$.each(getReq, function(id, key) {
alert(key+'='+id);
});
i want to travers it one by one.
here i can not get anything?
Upvotes: 1
Views: 135
Reputation: 276276
Yeah, your json
is wrong. It evaluates to the string "[[object Object]]"
because you are adding a string "[" and "]" to a JavaScript object (the part within the {}s)
Try
var obj = [{"lead_req_id":"","listing_id_1_ref":"RH-R-17","listing_id_1":"17"}]
There isn't any need to parse it now. It's already a JavaScript object.
If you want a JSON version of it, you can call JSON.stringify
on it:
Which results in:
'[{"lead_req_id":"","listing_id_1_ref":"RH-R-17","listing_id_1":"17"}]'
Upvotes: 1
Reputation: 28685
Your json format is invalid. try change your var json = ..
to:
var json = '[{"lead_req_id":"","listing_id_1_ref":"RH-R-17","listing_id_1":"17"}]';
Upvotes: 0
Reputation: 1038710
What you have shown here is not a JSON string. Here's how a valid JSON string would look like:
var json = '[{"lead_req_id":"","listing_id_1_ref":"RH-R-17","listing_id_1":"17"}]';
Now you can parse it:
var getReq = jQuery.parseJSON(json);
$.each(getReq, function(index, element) {
$.each(element, function(key, value) {
console.log(key + '=' + value);
});
});
If on the other hand you already had a javascript variable, then you don't need to be parsing anything, you could directly access it:
var getReq = [{"lead_req_id":"","listing_id_1_ref":"RH-R-17","listing_id_1":"17"}];
$.each(getReq, function(index, element) {
$.each(element, function(key, value) {
console.log(key + '=' + value);
});
});
Also notice that I have used 2 $.each
statements because the JSON string you have shown represents an array of some objects. The first loop goes through the array whereas the inner loop goes through the properties of each object in the array.
Upvotes: 3