1

My question: How can I parse a json array?

I send it like this:

$data= mysql_fetch_array($r);
header('Content-type: application/json');

?>              
{
    "check": "<?php echo $check?>",
    "productcode": "<?php echo $code?>",
     "values": [<?php echo $data?>]
}
<?php

on the ajax side I do this on the single values which works fine

success: function(data,textStatus){
    //return values
    identification=data.check;

if I want to access the array I do something like this and I get undefined

value=data.values[1];

What am I doing wrong?

1
  • Yeh, I heard that yesterday I really don't want to offend anybody. Sorry, I never payd much attention, to those things on the left sight. I will do that from now on. I really did not know at first why I was offending anyone, because I always say thank you. Commented Oct 12, 2009 at 12:39

3 Answers 3

1

You need to encode your array as JSON, too:

{
    "check": "<?php echo $check?>",
    "productcode": "<?php echo $code?>",
     "values": [<?php echo json_encode($data); ?>]
}

The easiest way is probably to put everything in a PHP array and serialize this as JSON:

$output = array(
    "check" => $check,
    "productcode" => $code,
    "values" => $data
);

echo json_encode($output);

Then you can be sure that it is being encoded properly.

Sign up to request clarification or add additional context in comments.

4 Comments

thanks, could you comment on the mysql_NUM, can I still get the values by name then, in ajax success function.
You could use mysql_fetch_assoc which returns an associative array. That means, that you then can access the columns in a row by its name in JavaScript (and not by its index). Just check the result and then you'll see what it does.
With msql_fetch_array, associative is the default, because I get my results by name, or both I get from @RC, s comment below.
Oh ok sorry. Well the manual said that MYSQL_NUM gives you a non associative array.
1

Try this:

$data= mysql_fetch_array($r);
header('Content-type: application/json');

$json = array(
    'check' => $check,
    'productcode' => $code,
    'values' => $data
    );

print json_encode($json);

It's more tidy than printing the json manually. json_encode turns a PHP array into a json string.

Comments

0
$data= mysql_fetch_array($r, MYSQL_NUM);

could correct the problem.

It would be helpful to get the json you get in the ajax part

2 Comments

what is it know then, an asociative? is associative bad for parsing?
according to the doc, it's both associative and num

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.