1

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?

2
  • 1
    Where is that object coming from? Why are you trying to parse it if it's already a JS object? Commented Apr 8, 2013 at 6:05
  • actually this is a json inside an other json,i am doing it like '['+json.property_req_1+']' and then want to traverse Commented Apr 8, 2013 at 6:15

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Your first code give me this error uncaught exception: Invalid JSON: [[object Object]]
You probably did something wrong. Here's a live demo: jsfiddle.net/MDHbh/1
1

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"}]'

Comments

0

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"}]';

http://jsfiddle.net/28UrL/1/

Comments

Your Answer

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