0

I am new to Json. please tell me how to access following element. this is my Json

var data = {"student":[{"fname":"mad", "sname":"cha"}, {"fname":"sun", "sname":"ban"}, {"fname":"sha", "sname":"kiri"}]};

so how I access to the "mad"value.

actually this is what I trying to do

<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<script>
    function click_me(){
        var data = {"student":[{"fname":"mad", "sname":"cha"}, {"fname":"sun", "sname":"ban"}, {"fname":"sha", "sname":"kiri"}]};
        localStorage.setItem('my_name',data);
        alert('OK');
    }

    function show_me(){
        var x = localStorage.getItem('my_name');
        x = x.student[0].fname;
        alert(x);
    }
</script>

</head>
<body>
  <input type="button" name="btn" value="Click" onclick="click_me()">
  <input type="button" name="btn" value="show_me" onclick="show_me()">
</body>
</html> 
user1784592
  • 129
  • 1
  • 3
  • 11

3 Answers3

2

It's

var yourValue = data.student[0].fname

By the way, this isn't JSON but a plain javascript object. JSON is a string based interchange format.


EDIT following your edit.

localStorage only stores strings. That's why getItem gives you a string in which you can't find your "mad".

Here's what you can do :

function click_me(){
    var data = {"student":[{"fname":"mad", "sname":"cha"}, {"fname":"sun", "sname":"ban"}, {"fname":"sha", "sname":"kiri"}]};
    localStorage.setItem('my_name', JSON.stringify(data));
    alert('OK');
}

function show_me(){
    var x = JSON.parse(localStorage.getItem('my_name')||"{}");
    x = x.student[0].fname; // it would be cleaner to test x.student exists
    alert(x);
}
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • @dystroy is right. The problem is localStorage. Here is one related post: http://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage store json with localStorage. But you don't need to use localStorage at all. – Gnijuohz Dec 04 '12 at 12:04
1

Access the value as follows:

var firstName = data.student[0].fname;

Example: http://jsfiddle.net/N8bSk/

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
1

you can do this by

  var yourValue = data.student[0].fname
user007
  • 71
  • 9