rahul.m
rahul.m

Reputation: 5854

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 of 1st json element price : "13000.0"

my code

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

but my output is '1'

Upvotes: 4

Views: 31807

Answers (8)

Yves Kipondo
Yves Kipondo

Reputation: 5603

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"]);

Upvotes: 3

rahul.m
rahul.m

Reputation: 5854

Following is the solution worked for my problem I use return false;

$.each(data_obj, function(index, element) {
     $('#price').append(element.price[0]);
     return false;
  });

Which gives only 1st value of array elements.

Upvotes: 0

saumil_
saumil_

Reputation: 323

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

Upvotes: 1

Ms.Tamil
Ms.Tamil

Reputation: 350

If you want only the first item's price, you don't need a loop here.

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

would work here.

For further reading you can refer here

Upvotes: 0

Loïs PEYTOUREAU
Loïs PEYTOUREAU

Reputation: 51

var my_first_json_obj = data_obj[0]; // Your first JSON obj (if it's an array of json object)
var my_price = my_first_json_obj.price; // Your price 
$('#price').append(my_price);

Upvotes: 0

Void Spirit
Void Spirit

Reputation: 909

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);

Upvotes: 0

Ali Shahbaz
Ali Shahbaz

Reputation: 845

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>

Upvotes: 4

jawahar N
jawahar N

Reputation: 482

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,

Upvotes: 0

Related Questions