简体   繁体   English

将文本数组转换为Javascript对象

[英]Converting text array to Javascript object

I'm trying to convert an array from a GET request to an actual object in Javascript. 我正在尝试将GET请求中的数组转换为Javascript中的实际对象。

This is an example of the array I'm trying to convert. 这是我要转换的数组的示例。

array(21) {
  [0]=>
  array(3) {
    ["id"]=>
    int(15508)
    ["name"]=>
    string(9) "Some name"
    ["API_key"]=>
    string(19) "Some key"
  }
  [1]=>
  array(3) {
    ["id"]=>
    int(19695)
    ["name"]=>
    string(12) "Some name"
    ["API_key"]=>
    string(19) "Some key"
  }
  [2]=>
  array(3) {
    ["id"]=>
    int(19627)
    ["name"]=>
    string(13) "Some name"
    ["API_key"]=>
    string(19) "Some key"
  }

The array is generated form a web service server in PHP. 该数组由PHP中的Web服务服务器生成。

I've tried to do this: 我试图做到这一点:

var result = xmlHttp.responseText;
var string = JSON.stringify(result);
var json = JSON.parse(string);

This returns the same array, but when I try to access certain items in the array for example in a for-loop: json[i] returns a single letter as if the array was a string. 这将返回相同的数组,但是当我尝试访问数组中的某些项(例如在for循环中)时: json[i]返回单个字母,就好像该数组是一个字符串一样。

I have control of the server, and this is the code in the php file that handles the returning of the array: 我控制了服务器,这是处理数组返回的php文件中的代码:

header("Content-Type: application/json");
var_dump($result);

Using gettype($result) returns 'array'. 使用gettype($result)返回“数组”。

Edit 编辑

I was able to get PHP to return the array in JSON format: 我能够得到PHP以JSON格式返回数组:

[
  [
    {
      "id": 15508,
      "name": "Some name",
      "API_key": "Some key"
    },
    {
      "id": 19695,
      "name": "Some name",
      "API_key": "Some key"
    },
    {
      "id": 19627,
      "name": "Some name",
      "API_key": "Some key"
    {
  ]
]    

I'm kinda new to this, and I would really appreciate any help. 我对此有些陌生,非常感谢您的帮助。

Try in PHP 试用PHP

$json = json_encode($_GET);
print_r($json);

And in JS 而在JS中

var result = xmlHttp.responseText;
var json = JSON.parse(result);

Update! 更新! I solved it this way 我这样解决了

By using the code in this answer, I was able to create JSON in PHP, as it turned out, my array was not properly encoded. 通过使用答案中的代码,事实证明,我无法在PHP中创建JSON,我的数组未正确编码。

$arr[] = $result;
function utf8ize($d) {
    if (is_array($d)) {
        foreach ($d as $k => $v) {
            $d[$k] = utf8ize($v);
        }
    } else if (is_string ($d)) {
        return utf8_encode($d);
    }
    return $d;

Then using echo json_encode(utf8ize($data)); 然后使用echo json_encode(utf8ize($data)); returns the array to JSON. 将数组返回JSON。 To transform it to JSON in JavaScript, I used the other answer here for help: 要将其转换为JavaScript中的JSON,我在这里使用了另一个答案来寻求帮助:

var result = xmlHttp.responseText;
var json = JSON.parse(result);

Thanks! 谢谢!

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

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