JSON PHP
Next ❯JSON Python
- PHP is a server side scripting language
- PHP also provides two methods to handle JSON data exchange
- Remember! All data exchange happen between client and sever are always in the form of string
- turned_in_notMethods
json_decode()
json_encode()
json_decode( )
Used to convert JSON String into an object
- Similar to
JSON.parse()
at client side
- Remember! You can also convert string like array via this method into an array
- turned_in_notjson_decode
OUTPUT<?php $jsonString = '{"name":"Rahul","love":"Music"}'; //Converting JSON String into an object $obj=json_decode($jsonString); //To access an object syntax (objectName->keyName) echo "My name is ".$obj->name; ?>
My name is Rahul
/* To access all key and values of an object inside PHP */
Key=name, Value=Rahul
Key=love, Value=Music
<?php
$jsonString = '{"name":"Rahul","love":"Music"}';
//Converting JSON String into an object
$obj=json_decode($jsonString);
//Accessing all key and values
foreach($obj as $key => $value) {
echo "Key=". $key .", Value=". $value ."<br>";
}
?>
json_encode( )
Used to convert an object into JSON String
- Similar to
JSON.stringify()
at client side
- Remember! You can also convert an array via this method into a string and send it to the client
- turned_in_notjson_encode
OUTPUT<?php class profile {} //Creating an object of class profile $obj=new profile(); $obj->name = "Rahul"; $obj->age = 23; $obj->love = "Music"; //Converting an object into JSON String $myJSON = json_encode($obj); echo "My JSON String is ".$myJSON; ?>
My JSON String is {"name":"Rahul","age":23,"love":"Music"}
- Remember! More like PHP, there are other server scripting languages that also provides similar JSON handling methods
Like in Python 3.X, in library 'json',
json.loads()
used asjson_parse()
andjson.dumps()
used asjson_stringify()
at server side
❮ Prev Stringify
Next ❯JSON Python