1

I am trying to parse the json object using jquery but it is giving me error that cannot get the length of a null object. I am not able to find the reason. Please help me in finding the issue. Here is what i am doing

            var slider_images = {
                "image": [
                            {"fname":"1", "caption":"this is 1"},
                            {"fname":"2", "caption":"this is 2"},
                            {"fname":"3", "caption":"this is 3"},
                            {"fname":"4", "caption":"this is 4"},
                            {"fname":"5", "caption":"this is 5"},
                            {"fname":"6", "caption":"this is 6"},
                            {"fname":"7", "caption":"this is 7"},
                            {"fname":"8", "caption":"this is 8"}
                        ]
            };

            var imageObj = $.parseJSON(slider_images.image);
            $.each(imageObj,function() {
                //alert("fname is::"+this['fname']);
                alert("1");
            });

I want to get the fname and caption for all the subobjects that fall under image. Please let me know where I am going wrong...

Thanks!

1
  • @Don: that does not work.... Andrew gave me the sol to it below... Commented Jan 13, 2013 at 5:10

1 Answer 1

4

Parsing JSON means converting a string into a JavaScript object. You already have an object so have nothing to 'parse'.

You can just use your object like this:

 $.each(slider_images.image, function() {
        console.log(this);
 });
Sign up to request clarification or add additional context in comments.

6 Comments

I kind of notice that but my eyes went to the comma error first
The comma will also cause problems in some browsers :)
@Andrew: In what case then i need to parse the JSON? Can you give me a small json object pointed so that I can understand when to parse it and when not...
@unix_user: Well you parse strings to json such as {"Greeting": "Hi"} and stringify objects to jsonstrings var jsonobj={greating: HiVarOrLitereal}
@unix_user If you want to send your object over HTTP for example you would first convert the whole object to a string using JSON.stringify(obj). If you have a string and want it turned back into an object, use JSON.parse(str) or your jQuery version. The JSON string looks like an object '{"a":1,"b":2}', but it's a string until you parse it. JSON is useful because you can send objects as strings. Does that make sense?
|

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.