简体   繁体   中英

Converting text array to Javascript object

I'm trying to convert an array from a GET request to an actual object in 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.

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.

I have control of the server, and this is the code in the php file that handles the returning of the array:

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

Using gettype($result) returns 'array'.

Edit

I was able to get PHP to return the array in JSON format:

[
  [
    {
      "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

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

And in 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.

$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)); returns the array to JSON. To transform it to JSON in JavaScript, I used the other answer here for help:

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

Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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