Tuesday, November 30, 2021

json_encode and json_decode in PHP




1) JSON stands for JavaScript Object Notation

Example of JSON string

s1 = '{"FirstName":"David", "LastName":"Lee"}'

It defines an object with 2 properties:  FirstName and LastName

JavaScript has a built in function for converting JSON strings into JavaScript objects:

obj = JSON.parse(s1)

After we  parse the JSON string with a JavaScript program, we can access the data as an object: 

let FirstName = obj.FirstName;
let LastName = obj.LastName

JavaScript also has a built in function for converting an object into a JSON string:

JSON.stringify()

2) PHP json_encode function

convert PHP array to JSON string

Example:

<?php
$arr 
= array('a' => 1'b' => 2'c' => 3'd' => 4'e' => 5);

echo 
json_encode($arr);
?>

The above example will output:

{"a":1,"b":2,"c":3,"d":4,"e":5}

3) PHP json_decode function 

json_decodeDecodes a JSON string to an object


<?php

$json 
'{"foo-bar": 12345}';

$obj json_decode($json);
print 
$obj->{'foo-bar'}; // 12345

?>

 3) Example in PHP Larvel

in controller

  $dataItems['FirstName'] = "David";

       $data['dataItems'] = json_encode($dataItems);

        return view('templates.view_layout', $data);

in view: view_layout.blade.php

       @isset($dataItems)
            <script type="text/javascript">
                var dataItems = {!! $dataItems !!};
            </script>
        @endisset
Parse to JavaScript object, which can be used it React.js

   constructor(props) {
        super(props);

        this.state = {
            data: dataItems ? dataItems : null,
       }

}

 //Access to FirstName

 this.state.data.FirstName;

 

 

 

 

No comments:

Post a Comment