To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.
parse() JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON. parse() , as the Javascript standard specifies.
To query JSON data, you can use standard T-SQL. If you must create a query or report on JSON data, you can easily convert JSON data to rows and columns by calling the OPENJSON rowset function. For more information, see Convert JSON Data to Rows and Columns with OPENJSON (SQL Server).
If your $result variable is a string json like, you must use json_decode function to parse it as an object or array:
$result = '{"Cancelled":false,"MessageID":"402f481b-c420-481f-b129-7b2d8ce7cf0a","Queued":false,"SMSError":2,"SMSIncomingMessages":null,"Sent":false,"SentDateTime":"\/Date(-62135578800000-0500)\/"}';
$json = json_decode($result, true);
print_r($json);
Array
(
[Cancelled] =>
[MessageID] => 402f481b-c420-481f-b129-7b2d8ce7cf0a
[Queued] =>
[SMSError] => 2
[SMSIncomingMessages] =>
[Sent] =>
[SentDateTime] => /Date(-62135578800000-0500)/
)
Now you can work with $json variable as an array:
echo $json['MessageID'];
echo $json['SMSError'];
// other stuff
References:
The main problem with your example code is that the $result variable you use to store the output of curl_exec() does not contain the body of the HTTP response - it contains the value true. If you try to print_r() that, it will just say "1".
The curl_exec() reference explains:
Return Values
Returns
TRUEon success orFALSEon failure. However, if theCURLOPT_RETURNTRANSFERoption is set, it will return the result on success,FALSEon failure.
So if you want to get the HTTP response body in your $result variable, you must first run
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
After that, you can call json_decode() on $result, as other answers have noted.
On a general note - the curl library for PHP is useful and has a lot of features to handle the minutia of HTTP protocol (and others), but if all you want is to GET some resource or even POST to some URL, and read the response - then file_get_contents() is all you'll ever need: it is much simpler to use and have much less surprising behavior to worry about.
Try:
$result = curl_exec($cURL);
$result = json_decode($result,true);
Now you can access MessageID from $result['MessageID'].
As for the database, it's simply using a query like so:
INSERT INTO `tableName`(`Cancelled`,`Queued`,`SMSError`,`SMSIncommingMessage`,`Sent`,`SentDateTime`) VALUES('?','?','?','?','?');
Prepared.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With