13

I am trying to map traceroutes to google maps.

I have an array in php with traceroute data as

$c=ip,latitude,longitude, 2nd ip, its latitude, longitude, ....target ip, its lat, its lng

I used json_encode($c, JSON_FORCE_OBJECT) and saved the file

Now, how do I access this using javascript, by directly equating it to new JS object?

earlier I used to have a data format like this on harddrive

var data12 = {

"route":[
{
    "ip": "some ip",

    "longitude": "some lng",

    "latitude": "some lat",

.....

and in my javascript it was used as

data=data12.route;

and then simply acces the members as data[1].latitude

J0HN
  • 26,063
  • 5
  • 54
  • 85

7 Answers7

27

I recommend using the jQuery library. The minified version only has 31 kB in size and provides lots of useful functions.

For parsing JSON, simply do

var obj = jQuery.parseJSON ( ' {"name" : "John"} ' );

You can now access everything easily:

alert ( obj.name );

Note: jQuery uses the browser's native JSON parser - if available - which is very quick and much safer then using the eval () method.

Edit: To get data from the server side to the client side, there are two possibilities:

1.) Use an AJAX request (quite simple with jQuery):

   $.ajax ( {
       url: "yourscript.php",
       dataType: "json",
       success: function ( data, textStatus, jqXHR ) {
           // process the data, you only need the "data" argument
           // jQuery will automatically parse the JSON for you!
       }
   } );

2.) Write the JSON object into the Javascript source code at page generation:

   <?php
       $json = json_encode ( $your_array, JSON_FORCE_OBJECT );
   ?>

   <script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>

   <script type="text/javascript">
   //<![CDATA[

   var json_obj = jQuery.parseJSON ( ' + <?php echo $json; ?> + ' );

   //]]>
   </script>
Sammy S.
  • 498
  • 5
  • 12
  • How do I get my csv data to the jquery routines? does Php json_encode work? Also, what If I have more than one traceroutes to encode? –  Aug 29 '11 at 10:54
  • You can simply use an AJAX request, if you want to load the data on a certain action or event. If you have access to the Javascript part in your web site for the PHP part, you could also write the JSON object into the Javascript file. Throw your array into PHP's `json_encode ()` function like this: `$json_obj = json_encode ( $your_array, JSON_FORCE_OBJECT );`. – Sammy S. Aug 29 '11 at 10:59
8

I know this is old, but I recently found myself searching for this. None of the answers here worked for my case, because my values had quotes in them. The idea here is to base64 encode the array before echo'ing to the page. That way the quotes don't conflict.

< ?php
$names = ['first' => "some'name"];
?>
var names = JSON.parse(atob('< ?php echo base64_encode(json_encode($names)); ?>'));
console.log(names['first']);
HoofHarted
  • 176
  • 2
  • 5
  • 1
    +1 for being the only answer not using some external library **and** coping with special characters that potentially break the resulting JavaScript string. Another approach is to escape the relevant characters using addcslashes in PHP: `var names = JSON.parse('');` – Arthur Apr 13 '19 at 12:58
1

I could get the JSON array by using PHP's json_encode() from backend like this example:

<!doctype html>
<html>
    <script type="text/javascript">
        var json = <?php echo json_encode(array(1 => '123', 'abc' => 'abd', 2 => 5));?>;
        console.log(json[1]);
        console.log(json.abc);
    </script>        
</html>

No quotation marks means an eval() of whatever was printed out. This is a quick hack that we utilised often to quickly add initial values to our AJAX page.

fred
  • 319
  • 2
  • 5
  • 17
  • That would set the variable "json" to a json string. The poster wanted a javascript object. I think you probably meant to leave off the quotation marks. Also this answer wouldn't really be applicable if the poster intends to use this for AJAX requests. – Tim Seguine Apr 18 '13 at 09:48
1

This function works for you I guess:

    function json_encode4js($data) {
    $result = '{';
    $separator = '';
    $count = 0;
    foreach ($data as $key => $val) {

        $result .= $separator . $key . ':';
        if (is_array($val)){
            $result .= json_encode4js($val).(!$separator && count($data) != $count ? ",":"");
            continue;
        }
        if (is_int($val)) {
            $result .= $val;
        } elseif (is_string($val)) {
            $result .= '"' . str_replace('"', '\"', $val) . '"';
        } elseif (is_bool($val)) {
            $result .= $val ? 'true' : 'false';
        } elseif (is_null($val)) {
            $result .= 'null';
        } else {
            $result .= $val;
        }

        $separator = ', ';
        $count++;
    }

    $result .= '}';

    return $result;
}

$a = array(
"string"=>'text',
'jsobj'=>[
    "string"=>'text',
    'jsobj'=>'text2',
    "bool"=>false
    ],
"bool"=>false);

var_dump( json_encode4js($a) ); //output: string(77) "{string:"text", jsobj:{string:"text", jsobj:"text2", bool:false}, bool:false}" 

var_dump( json_encode($a));//output: string(85) "{"string":"text","jsobj":{"string":"text","jsobj":"text2","bool":false},"bool":false}"
mort
  • 12,988
  • 14
  • 52
  • 97
0

no need for jquery, just:

    var array= <?php echo json_encode($array); ?>;
    console.log(array->foo);
Sebastian Viereck
  • 5,455
  • 53
  • 53
0

we have to display the json encode format in javascript , by using below one:

var responseNew = JSON.parse(' {"name" : "John"} ' );
alert(responseNew['name']);
Elangovan
  • 3,469
  • 4
  • 31
  • 38
0

HTML

<select name="sub" id="subcat" class="form-control" required="required">

</select>

PHP

$this->load->model('MainModel');
$subvalue = $this->MainModel->loadSubData($var);
echo json_encode($subvalue);
//if MVC
// or you can just output your SQLi data to json_encode()

JS

$("#maincat").change(function(){
  var status = this.value;

  $.ajax({
    type: 'POST',
    url: 'home/subcat/'+status,
    success: function(data){
        var option = '';
        var obj = JSON.parse(data);
        if(obj.length > 0){
            for (var i=0;i<obj.length;i++){
            option += '<option value="'+ obj[i].id + '">' + obj[i].name + '</option>';  
            }
            //Now populate the second dropdown i.e "Sub Category"
            $('#subcat').children("option").remove();
            $('#subcat').append(option);
        }else{
            option = '<option value="">No Sub Category Found</option>';
            $('#subcat').children("option").remove();
            $('#subcat').append(option);
        }       
    },
    error: function(){
    alert('failure');
    }
});
Tayyab Hayat
  • 815
  • 1
  • 9
  • 22