0

Below is the sample json data that i took from my api in html page,

[{
    "id": 1,
    "name": "rele",
    "location": "bedroom",
    "posts": [
        {
            "id": 2,
            "description": "hi"
        }
    ]
}]

Below is the jquery,

<script type = "text/javascript" >
     $(document).ready(function() {

        $("#message").click(function(event){
           $.getJSON('http://localhost:8080/jpa/device', function(jd) {
              $('.tblForm #result').html('<p> ID: ' + jd.posts.id + '</p>');
              $('.tblForm #result').append('<p>Description : ' + jd.posts.description+ '</p>');

           });
        });

     });
  </script>

i could able to fetch name and location value but not posts.description.

I am getting an error : "Property or field 'description' cannot be found"

Praveen
  • 1,791
  • 3
  • 20
  • 33
Amir
  • 3
  • 2
  • 2
    `posts` is an array so you need to access it by index, or loop through it. try `jd.posts[0].description` to get the first element of the array – Rory McCrossan Aug 10 '18 at 14:56

1 Answers1

0

your "posts" var is a list, so you'd better do a loop on it by replacing this code :

$('.tblForm #result').append('<p>Description : ' + jd.posts.description+ '</p>');

By this one :

$.each(jd.posts, function(index, post){
    $('.tblForm #result').append('<p>Description : ' + post.description+'</p>');
});

Here I use an index var which may be useless for you just to let you know it exists, in case you want to add odd or even css attributes to your code for example.