Nikola
Nikola

Reputation: 15048

jQuery parseJSON returns double data

I have a PHP file which returns this:

$data = pg_fetch_array($result);
echo json_encode($data);

And in the .js code i do this:

var jsonObj = $.parseJSON(text);
console.dir(jsonObj);

And my problem is I get this "double" data:

{"0":"3","id":"3","1":"test","type":"test","2":"google","name":"google", "3":"http://www.google.com","url":"http://www.google.com"}

Any ideas on how to retrieve it without those indexes (0,1,2...)?

Upvotes: 0

Views: 308

Answers (3)

Janis Veinbergs
Janis Veinbergs

Reputation: 6988

The problem is not in parseJSON method but in pg_fetch_array. And it is the expected behaviour.

PHP Documentation says that pg_fetch_array by default "indexed numerically (beginning with 0) or associatively (indexed by field name)" so you can access values either by index or by name.

To change this behaviour, use either

$data = pg_fetch_array($result, 0, PGSQL_ASSOC); //Keys are names only
$data = pg_fetch_array($result, 0, PGSQL_NUM); //Keys are indexes only

Upvotes: 2

Wolfgang Kuehn
Wolfgang Kuehn

Reputation: 12926

Try pg_fetch_array($result, NULL, PGSQL_ASSOC);

Upvotes: 0

Sandeep Manne
Sandeep Manne

Reputation: 6092

I think you dont need to parse that using json, if you are using jquery ajax method then just mention dataTye: json, then you can directly access that object.

Upvotes: 0

Related Questions