How to Convert a String to JSON Object in PHP ?
Last Updated :
17 Jan, 2024
Given a String, the task is to convert the given string into a JSON object in PHP. JSON (JavaScript Object Notation) is a widely used data interchange format. PHP provides convenient functions to work with JSON data.
Approach 1: Using json_decode() to Convert to an Array
The json_decode() function is a versatile and commonly used method to convert a JSON-formatted string into a PHP object.
PHP
<?php
$jsonString = '{"key1": "value1", "key2": "value2", "key3": "value3"}' ;
$phpObject = json_decode( $jsonString );
print_r( $phpObject );
?>
|
Output
stdClass Object
(
[key1] => value1
[key2] => value2
[key3] => value3
)
Approach 2: Handling Errors with json_last_error() and json_last_error_msg() Methods
It’s essential to handle errors that may occur during the decoding process. The json_last_error() function returns the last error occurred, and json_last_error_msg() provides a human-readable error message.
PHP
<?php
$jsonString = '{"key1": "value1", "key2": "value2", "key3": "value3"}' ;
$decodedData = json_decode( $jsonString );
if ( $decodedData === null) {
echo "Error decoding JSON: "
. json_last_error_msg();
} else {
print_r( $decodedData );
}
?>
|
Output
stdClass Object
(
[key1] => value1
[key2] => value2
[key3] => value3
)
Share your thoughts in the comments
Please Login to comment...