Skip to content Skip to sidebar Skip to footer

How To Get Only 1st Element Of JSON Data?

I want to fetch only 1st element of json array my json data : { id:'1', price:'130000.0', user:55, } { id:'2', price:'140000.0', user:55, } i want to access the price

Solution 1:

Assuming that you have array of objects

var arr = [{  
      id:"1",
      price:"130000.0",
      user:55,
     },
     {  
       id:"2",
       price:"140000.0",
      user:55,
     }]

     console.log(arr[0].price)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Solution 2:

You data isn't valid JSON, JSON data key must be wrap within double quote, but your data isn't wrapped in double quote

var data = [{  
    "id":"1",
    "price":"130000.0",
    "user":55
},{  
    "id":"2",
    "price":"140000.0",
    "user":55
}]

console.log(data[0]["price"]);

Solution 3:

Hello You just need to add [] from starting and ending point of your json string. see here var data = JSON.parse( '[{ "id":"1","price":"130000.0","user":55},{"id":"2","price":"140000.0","user":55}]');

var priceValue = 0;
$.each(data, function(index, element) {if(index == 0){  priceValue =    element.price;}});console.log(priceValue);

Your answer will be 13000.0


Solution 4:

The element having the your JSON data means, we can able to use below code to get the first JSON data.

element[0].price

Thanks,


Solution 5:

You are using for each loop and in function you get 2 params first one is index and second is the element itself. So this will iterate through all elements.

$.each(data_obj, function(index, element) {
      $('#price').append(element.price);
});

If you just want to get first element

$('#price').append(data_obj[0].price);

Post a Comment for "How To Get Only 1st Element Of JSON Data?"