简体   繁体   中英

How to access to given element in Json

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> 

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

Access the value as follows:

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

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

你可以这样做

  var yourValue = data.student[0].fname

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM