Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

How json's key is called when the number is called


May 08, 2021 JSON



This article describes how JSON's keys should be called when they are named numbers, and for keys named numbers or abnormal variable characters (if there are spaces), you must use the obj.xx method to get the value.

The code is as follows:
<?php
//声明json数据
$array = array('result'=>array("90"=>"90队列","status"=>"成功"));
$json = json_encode($array);
$array1 = array("90"=>"90队列","status"=>"成功");
$json1 = json_encode($array1);
$phpjson = json_decode($json1,true);//第二个参数是true,表示把json数据转换为数组
//对于json键名是数字时,只能用数组方式处理$phpjson['90'];
?>
<!DOCTYPE unspecified PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>
<script type="text/javascript">
/**
* 测试json数据调用示例
*/
function test(){
//调用方式一
var data = '<?php echo $json?>';//php json数据,这里只能用单引号,因为php的json数据中有双引号了
data = eval("("+data+")");//js 解析json数据,主要是因为json数据用单引号后变为字符串了
alert(data['result'][90]);//对于数字需要用数组的方式访问
alert(data['result'].status);//对于非数字可以使用.的方式访问
//调用方式二
var data1 = <?php echo $json1?>;//php json数据,这里没有用单引号,因为直接是json数据
alert(data1[90]);//对于数字需要用数组的方式访问
alert(data1.status);//对于非数字可以使用.的方式访问
alert(data1['status']);//还可以使用数组方式调用
//注:对于键名为数字或者非正常变量字符时(如有空格),必须使用obj[xx]方式获取值。
}
</script>
<input type="button" value="button" onclick="test();"/>
</body>
</html>

js gets the key name and value of the json object

Encountered the json object, the key name is not fixed, and then do not know how to take, the monitor below an object, there is no property method. Here's how:

d = {"1": "a", "2": "b"}
for(i in d)
{
   i 就是键,d[i]就是值
}

It's hard not, it's not hard.

Here's an example:
<script>
d = {"1": "a", "2": "b"}
function GetJArray(selIndex,arr){
 
   var index =0;
    for(i inarr)
    {
      if(index == selIndex){
         //i就是键,arr[i]就是值
        document.write(i + ',' + arr[i] +'<br/>');
      }
      index +=1;
    }
}
GetJArray(1,d);
  </script>