简体   繁体   English

如何访问Json中的给定元素

[英]How to access to given element in Json

I am new to Json. 我是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. 所以我如何获得"mad"价值。

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,而是普通的javascript对象。 JSON is a string based interchange format. JSON是基于字符串的交换格式。


EDIT following your edit. 编辑后进行编辑。

localStorage only stores strings. localStorage仅存储字符串。 That's why getItem gives you a string in which you can't find your "mad". 这就是为什么getItem为您提供一个字符串,在其中您找不到“疯子”的原因。

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/ 示例: http//jsfiddle.net/N8bSk/

你可以这样做

  var yourValue = data.student[0].fname

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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