无法将json对象转换为2D数组

时间:2017-01-17 08:24:12

标签: javascript jquery arrays json

我有一个JSON对象:

var info=JSON.parse(server_response);

我跑console.log(info); 得到了这个输出:

[  
  [  
    [  
      "Dipu",
      "Mondal",
      "O Positive",
      "017xxxx",
      "AIS"
    ]
  ],
  [  
    [  
      "dipu",
      "Roy",
      "O Positive",
      "017xxxx",
      "Electrical"
    ]
  ],
  [  
    [  
      "Dhinka",
      "Chika",
      "O Positive",
      "9038485777",
      "stat"
    ]
  ]
]

跟着这个小提琴:http://jsfiddle.net/6CGh8/我试过了:

console.log(info.length); //output: 161
console.log(info[0].length); //output: 1
console.log(info[0][1]); //output: undefined

这三条线的预期输出(分别):

  

3
5
迪普

为什么我期待这个:

此JSON对象包含3个数组,每个数组中有5个数据,[0][1]元素为Dipu

如何获得预期的输出?

2 个答案:

答案 0 :(得分:5)

你有json编码两次,所以info只是一个文本,而不是一个数组。

info.length    // length of the string
info[0].length // length of a character (1)
info[0][1]     // undefined because a character is not an array

尝试var info = JSON.parse(JSON.parse(server_response))

答案 1 :(得分:1)

您的轻描淡写和JSON结构存在一些错误。

  1. 你的JSON数据被限制在数组中两次不需要(这将纠正第一个要求)
  2. info [0] [1]实际上并非 Dipu Mondal 。 info [0] [1]表示数组info [0]的第二个元素。您需要将其更改为info [0] [0]以访问第一个数组的第一个元素,即 Dipu
  3. 您的JSON结构需要修改为

    [["Dipu","Mondal","O Positive","017xxxx","AIS"],
     ["dipu","Roy","O Positive","017xxxx","Electrical"],
     ["Dhinka","Chika","O Positive","9038485777","stat"]]
    

    以下是示例代码段

    
    
    <!doctype html>
    <html lang="en">
    
    <head>
        <script>
            var info = JSON.parse('[["Dipu","Mondal","O Positive","017xxxx","AIS"],["dipu","Roy","O Positive","017xxxx","Electrical"],["Dhinka","Chika","O Positive","9038485777","stat"]]');
            console.log(info.length); //OP: 3
            console.log(info[0].length); //OP: 5
            console.log(info[0][0]); //OP: Dipu
        </script>
    </head>
    
    <body>
    
    </body>
    
    </html>
    &#13;
    &#13;
    &#13;