Reputation: 129
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>
Upvotes: 0
Views: 57
Reputation: 382514
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);
}
Upvotes: 2
Reputation: 94499
Access the value as follows:
var firstName = data.student[0].fname;
Example: http://jsfiddle.net/N8bSk/
Upvotes: 1