0

guys i know it is dummy question but i spent a lot of hours and cant reach .. i ha ve json array and i want for example to access the elements of second row which are lname2 fname2 90 feedback2 .. this is the array var json = [ { "lname" : "lname1", "fname" : "fname1", "age" : 10, "feedback" : "feedback1" }, { "lname" : "lname2", "fname" : "fname2", "age" : 90, "feedback" : "feedback2" }, { "lname" : "lname3", "name" : "fname3", "age" : 30, "feedback" : "feedback3" }

dina saber
  • 103
  • 2
  • 12

4 Answers4

1

You have an array of objects - so iterate the array, access the object properties:

for (var i = 0; i < json.length; i++) {
    console.log(json[i].fname);
}

To specifically access the second element of the array, specify the index:

var fname = json[1].fname;
tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

You can access 2nd row by index

json[1] 
Jagdish Idhate
  • 7,513
  • 9
  • 35
  • 51
0

Use the below code

json[1].lname
json[1].fname
json[1].age
json[1].feedback

Also what ever you have posted is not a JSON its an parsed result of JSON. JSON is ultimately a string. all the data is converted into one big string. Later when you parse the json you will get the result as in your post.


Explaining the code

Note that variable json is like var json = [] , this [ ] is used to create a array, Hence the variable json is an array and we can access the elements by inex

Here [1] referes to the index of the array. As your json is an array. We use index numbers to access the elements in the array. And the indexes start from 0. So your second element will be in the index 1, 3rd will be in 2 and so on...

Now json[1] will return the second element so..

 json[1] = {
            "lname" : "lname2",
            "fname" : "fname2",
            "age" : 90,
            "feedback" : "feedback2"
        }

note the { } this refers to an object, this { } is used to create an object. Now to access the property values of the object we use the . operator. hence the code json[1].lname , json[1].fname and so on..

Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59
0

From what I can see, this variable is not a JSON, but simply a javascript array of objects. To access a data in it, you'll have to use json[X].lname for exemple, where X is the index of the object you want to reach.

A JSON is a string of characters representing different type of data, such as arrays and objects. To decode such a string, you could use JSON.parse().

You can find more informations about JSON here : http://www.json.org/

Hope this helps!

RaphBlanchet
  • 575
  • 6
  • 23