tags:

views:

118

answers:

4

I want to get a fair idea about json format... I am using php in which i have converted my result array to json like this

$result = mysql_query("select dStud_id,dMarkObtained1,dMarkObtained2,
                dMarkObtained3,dMarkTotal from tbl_internalmarkallot");
$JsonVar = json_encode($res);

echo "<input type='text' name='json' id='json' value ='$JsonVar'>";

And the text box shows

{"0":"101","dStud_id":"101","1":"60","dMarkObtained1":"60","2":"80", "dMarkObtained2":"80","3":"80","dMarkObtained3":"80","4":"220","dMarkTotal":"220"}

Is this a correct json format....

+7  A: 

There is an online JSON validator and it sais that it is valid JSON. If you use JSON more often I would recommend the JSON View firefox plugin.

Daff
Awesome plugin! I got into a nasty habit of turning off the application/json header when debugging, this is much better.
Jasper De Bruijn
A: 

The json parser on http://json.parser.online.fr/ says this is valid json.

Janusz
A: 

it's correct but you're better off using something like this:

<?php
  $myResultArray = array();
  $result = mysql_query("select dStud_id,dMarkObtained1,dMarkObtained2, dMarkObtained3,dMarkTotal from tbl_internalmarkallot");

  while ($row = mysql_fetch_array($result)) {
    static $i = 0;
    $myResultArray[$i] = $row;
    $i++;
  }

  $JsonVar = json_encode($myResultArray);

  echo '<input type="text" name="json" id="json" value="'.$JsonVar.'">';
?>
n00b
+1  A: 

That particular string is valid JSON. However:

echo "<input type='text' name='json' id='json' value ='$JsonVar'>";

is missing a call to htmlspecialchars, so if there happens to be a single quote in one of your values, you've got a broken attribute, resulting in invalid JSON and HTML-injection, leading to potential XSS security holes.

Remember to HTML-escape every text string you output into HTML, eg.:

<input type="text" name="json" id="json" value="<?php echo htmlspecialchars($JsonVar); ?>">

or, you can use the PHP 5.3 JSON_HEX options to ensure HTML-special characters are not present, avoiding the need for this step:

<?php $jsonVar= json_encode($res, JSON_HEX_TAG|JSON_HEX_QUOT|JSON_HEX_AMP); ?>
<input type="text" name="json" id="json" value="<?php echo $jsonVar; ?>">
bobince