How to access an array in a JSON object?

后端 未结 8 977
感动是毒
感动是毒 2020-12-15 05:35

I have the following JSON object:

[
    {
        "comments": [
            {
                "created_at": "2011-02-09T14:42:42-08:0         


        
相关标签:
8条回答
  • 2020-12-15 06:02

    Do something like this:-

    var dataJS = [{"comments":[{"created_at":"2011-02-09T14:42:42-08:00","thumb":"xxxxxxx","level":1,"id":214,"user_id":41,"parent_id":213,"content":"<p>xxxxxx</p>","full_name":"xx K"},{"created_at":"2011-02-09T14:41:23-08:00","thumb":"xxxxxxxxxxxxx","level":0,"id":213,"user_id":19,"parent_id":null,"content":"<p>this is another test</p>","full_name":"asd asd asd asd asd"}],"eee1":"asdadsdas","eee2":"bbbbb"}];
    
    var created_at = dataJS[0].comments[0].created_at;
    
    0 讨论(0)
  • 2020-12-15 06:03

    JSON must be interpreted with eval function (after the obvious sanitization, see security considerations of eval). Are you sure your framework does that for you?

    0 讨论(0)
  • 2020-12-15 06:09

    Yes, as others have stated, the JSON is actually an Array (of a single Object). So you will need to reference an index.

    Interestingly enough (to me), your result string does validate successfully as JSON. I assumed until now, that to be valid JSON, it had to be an Object (ie, {}).

    0 讨论(0)
  • 2020-12-15 06:15

    That's because your base object is an array as well.

    console.log(dataJS[0].comments[0]);
    

    I suspect that would work

    0 讨论(0)
  • 2020-12-15 06:16

    The object being returned is itself an array, so to get to the first comment (as an example), this is how you would access it:

    dataJS[0].comments[0]

    0 讨论(0)
  • 2020-12-15 06:22

    You have to mention the dataType in the ajax request as 'JSON'. Make user you did that like below.

     $.ajax({
                url: $('#frmAddCourse').attr('action'),
                type: 'POST',
                data: $('#frmAddCourse').serialize(),
                dataType: 'JSON',
                success: function (data){
                    Materialize.toast(data['state'],2000);
                },
                error:function(){
                    Materialize.toast(errorMessage,2000);
                }
            });
    
    0 讨论(0)
提交回复
热议问题