Unable to parse a string into JSON object, unable to display an alert box from javascript
html, javascript, json, php
Solution
If you don't put it as a string it would be an object and you would not have to parse it
var jsonObj = <?php echo json_encode($rowarr); ?>;
instead of
var jsonString = '<?php echo json_encode($rowarr); ?>';
var jsonObj = jQuery.parseJSON( jsonString );
It looks like document.onload doesn't fire/already fired? you should use `window.onload` or `$(document).ready()` instead.
Problem
EDIT: SOLVED. Use any of the solutions below, but document.onload needs to be changed to window.onload. Also works without needing window.onload function anyway. Here is the test.php file that i'm working with ``` <?php include("conn.php"); ?> <!DOCTYPE html> <html> <head> <title>test</title> </head> <body> <script src="js/jquery.js"></script> <script type="text/javascript"> document.onload = function (){ var jsonString = '<?php echo json_encode($rowarr); ?>'; var jsonObj = jQuery.parseJSON( jsonString ); console.log(jsonObj); alert( jsonObj.Auckland ); }; </script> </body> </html> ``` I have verified in Chrome Developer tools the value of jsonString to be ``` '{"Auckland":37616,"Wellington":35357,"Christchurch":29818}' ``` After that I don't get any log on the console or any alert box. I have also tried JSON.parse method instead of jQuery.parseJSON to no avail. I'm trying to get this JSON into a datatable format used for google charts geo chart which looks like this bit of code ``` var data = google.visualization.arrayToDataTable([ ['City', 'Population', 'Area'], ['Rome', 2761477, 1285.31], ['Milan', 1324110, 181.76], ['Naples', 959574, 117.27], ['Turin', 907563, 130.17], ['Palermo', 655875, 158.9], ['Genoa', 607906, 243.60], ['Bologna', 380181, 140.7], ['Florence', 371282, 102.41], ['Fiumicino', 67370, 213.44], ['Anzio', 52192, 43.43], ['Ciampino', 38262, 11] ]); ```