json_decode fails to decode json data - php

In GitLab web hooks this is the json they give as an example.
{
"before": "95790bf891e76fee5e1747ab589903a6a1f80f22",
"after": "da1560886d4f094c3e6c9ef40349f7d38b5d27d7",
"ref": "refs/heads/master",
"user_id": 4,
"user_name": "John Smith",
"project_id": 15,
"repository": {
"name": "Diaspora",
"url": "git#localhost:diaspora.git",
"description": "",
"homepage": "http://localhost/diaspora",
},
"commits": [
{
"id": "b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327",
"message": "Update Catalan translation to e38cb41.",
"timestamp": "2011-12-12T14:27:31+02:00",
"url": "http://localhost/diaspora/commits/b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327",
"author": {
"name": "Jordi Mallach",
"email": "jordi#softcatala.org",
}
},
{
"id": "da1560886d4f094c3e6c9ef40349f7d38b5d27d7",
"message": "fixed readme",
"timestamp": "2012-01-03T23:36:29+02:00",
"url": "http://localhost/diaspora/commits/da1560886d4f094c3e6c9ef40349f7d38b5d27d7",
"author": {
"name": "Code Solution dev user",
"email": "gitlabdev#dv6700.(none)",
},
},
],
"total_commits_count": 4,
}
I've placed this in a file test.json.
I'm calling this with file_get_contents() then trying to decode but I'm getting nothing back at all.
$test = file_get_contents('test.json');
$json = json_decode($test);
echo "<pre>";
print_r($json);
echo "</pre>";
returns:
<pre></pre>
Any ideas why json_decode() is failing to decode?

It is because of a stray comma. You should check for errors:
if (json_last_error() != JSON_ERROR_NONE) {
die(json_last_error_msg());
}
If you have PHP <5.5.0 then you can use this compatibility function:
if ( ! function_exists('json_last_error_msg')) {
function json_last_error_msg() {
static $errors = array(
JSON_ERROR_NONE => null,
JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch',
JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded'
);
$error = json_last_error();
return array_key_exists($error, $errors) ? $errors[$error] : "Unknown error ({$error})";
}
}

Actually it wasn't stray commas as the answerers suggested, JSONLint reported BOM artifacts from UTF-8, I'm assuming from copying and pasting.
Once I ran it through and removed the BOM artifacts it decoded properly.
Thanks to all for your help and suggestions.

Related

PHP fails to parse JSON - Unexpected Integer

I'm trying to make an application that will use a JSON input. Below is some code that shows the problem when run. The problem being a syntax error; unexpected integer from the "etag" line ("$etag": "W/\"datetime'2019-10-31T23%3A22%3A09.7835369Z'\"",). When I remove the etag line it runs fine but otherwise I get an error. Can I remove the etag line (not needed anyway) before being parsed or get around it some other way? I unfortunately cant change what the API sends.
<?php
$json = '{
"Form": {
"Id": "1",
"InternalName": "SignUp",
"Name": "Sign Up"
},
"$version": 7,
"$etag": "W/\"datetime'2019-10-31T23%3A22%3A09.7835369Z'\"",
"Email": "test#email.com",
"Phone": "(123) 412-3412",
"CarrierServiceProvider": "Sprint",
"WTSKeywords": "Testing WTS",
"WTBKeywords": "Testing WTB",
"Id": "1-3",
"Email_IsRequired": false,
"Phone_IsRequired": false,
"CarrierServiceProvider_IsRequired": true
}';
$data = json_decode($json);
echo $data->Email;
echo "\n";
echo $data->WTBKeywords;
?>
Code should output: test#email.com Testing WTB
You json string has both ' and ", so you cannot simple use single or double quoted.
Use heredoc like this,
$json = <<<EOT
{
"Form": {
"Id": "1",
"InternalName": "SignUp",
"Name": "Sign Up"
},
"$version": 7,
"$etag": "W/\"datetime'2019-10-31T23%3A22%3A09.7835369Z'\"",
"Email": "test#email.com",
"Phone": "(123) 412-3412",
"CarrierServiceProvider": "Sprint",
"WTSKeywords": "Testing WTS",
"WTBKeywords": "Testing WTB",
"Id": "1-3",
"Email_IsRequired": false,
"Phone_IsRequired": false,
"CarrierServiceProvider_IsRequired": true
}
EOT;
$data = json_decode($json);
echo $data->Email;
echo "\n";
echo $data->WTBKeywords;

PHP 7.2 json_decode()

I have this string that was working with json_decode() with PHP 5.6 but doesn't work with PHP 7.2?
$json = '
{
"text": "Hi {{fname}}
Welcome to our customer support.
Please select language to proceed",
"buttons": [
{
"text": "English",
"value": "language_english",
"type": "postback"
},
{
"text": "Germany",
"value": "language_germany",
"type": "postback"
}
]
}';
I have tried replacing the whitespaces and newline like this
$json = preg_replace("/\n/m", '\n', $json);
$what = "\\x00-\\x19"; // all whitespace characters except space itself
$json = trim(preg_replace( "/[".$what."]+/" , '' , $json));
Which results into a string like this
\n{\n "text": "Hi {{fname}} \n Welcome to our customer support. \n Please select language to proceed",\n "buttons": [\n {\n "text": "English",\n "value": "language_english",\n "type": "postback"\n },\n {\n "text": "Germany",\n "value": "language_germany",\n "type": "postback"\n }\n ]\n}
Notice the \n in between and outside double quotes which makes it an invalid json and hence json_decode won't work in this case.
Does anyone know a way to achieve this?
Thank you.
{
"text": "Hi {{fname}} \n Welcome to our customer support. \n Please select language to proceed",
"buttons": [{
"text": "English",
"value": "language_english",
"type": "postback"
},
{
"text": "Germany",
"value": "language_germany",
"type": "postback"
}
]
}
This is a valid json. i added line breaks so you can use them if you want to print the messages in browser.
You can use this nice tool to validate your json when you have doubts.
Editing my answer based on comment feedback.
First of all the right step is that you figure out why you have a broken json in the database. If it's not on you and you have to fix it in php then a solution could be like this:
<?php
echo '<pre>';
$data = '
{
"text": "Hi {{fname}}
Welcome to our customer support.
Please select language to proceed",
"buttons": [
{
"text": "English",
"value": "language_english",
"type": "postback"
},
{
"text": "Germany",
"value": "language_germany",
"type": "postback"
}
]
}';
if (strstr($data, "\n")) {
$data = trim(preg_replace('/\s\s+/', ' ', $data));
}
echo $data;
Above code will capture the line breaks of your text field, and replace them with DOUBLE space. Then you will get a valid json like:
{
"text": "Hi {{fname}} Welcome to our customer support. Please select language to proceed",
"buttons": [
{
"text": "English",
"value": "language_english",
"type": "postback"
},
{
"text": "Germany",
"value": "language_germany",
"type": "postback"
}
]
}
What you can do if you need the line breaks is that you decode your json (just like you want and replace the double spacing in text field with a line break

Getting data from json and passing to url

Want to send the json data to my url, when the json is received i receive all the json data on the url and not the data from 'resolvedQuery'
$update_response = file_get_contents("php://input");
$update = json_decode($update_response, true);
$results = $update['result']['resolvedQuery'];
$url = "https://autoremotejoaomgcd.appspot.com/sendmessage?key=APA91bEq&message=Data" . urlencode(json_encode($update));
Json Data
{
"id": "4ed272a3-b9a4-4f18-a67e-10e12e4f4149",
"timestamp": "2017-12-10T10:07:54.282Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "turn livingroom light on",
"action": "",
"actionIncomplete": false,
"parameters": {
"power-toggle": "on",
"room": "livingroom"
},
"contexts": [],
"metadata": {
"intentId": "19764ecc-715c-4b25-960f-9845f2aef1f9",
"webhookUsed": "true",
"webhookForSlotFillingUsed": "false",
"webhookResponseTime": 503,
"intentName": "lights"
},
"fulfillment": {
"speech": "Ok, Turning livingroom light on",
"messages": [
{
"type": 0,
"speech": "Ok, Turning livingroom light on"
}
]
},
"score": 1
},
"status": {
"code": 206,
"errorType": "partial_content",
"errorDetails": "Webhook call failed. Error: Webhook response was empty.",
"webhookTimedOut": false
},
"sessionId": "395d3517-05da-42ac-9037-dadac519ab0b"
}
How do i get data from 'resolvedQuery' and send it to my URL
In the code you provided, you have the following line of code
$url = "https://autoremotejoaomgcd.appspot.com/sendmessage?key=APA91bEq&message=Data"
. urlencode(json_encode($update));
You are appending to the URL parameter message the results of json_decode($update_response, true). $update_response contains all the decoded JSON data posted by the HTTP request which is not what you want.
I believe what you want is a new parameter called resolved-query to be set to the results of json_decode($result, true).
Try chaninging your $url variable to the following:
$url = "https://autoremotejoaomgcd.appspot.com/sendmessage?key=APA91bEq&message=Data&resolved-query="
. urlencode(json_encode($result));
URL will be set to the following string:
https://autoremotejoaomgcd.appspot.com/sendmessage?
key=APA91bEq&
message=Data&
resolved-query=turn+livingroom+light+on

smsgateway.me store message status in php variable

Using smsgateway.me to send a message I use the default code with my own variables which are working fine. However, sometimes the SMS does not send and I would like to store the SMS in the database if failed.
To do so I think I need a value from the $result array, but I dont know how to start. I tried many different codes without any result.
Can anywone please tell me how to get an if sent ok -> do something / else do something else based on the code and variables below?
Thanks a lot!
Documentation here
Here is the default code (with default variables) that sends a message:
<?php
include "smsGateway.php";
$smsGateway = new SmsGateway('demo#smsgateway.me', 'password');
$deviceID = 1;
$number = '+44771232343';
$message = 'Hello World!';
$options = [
'send_at' => strtotime('+10 minutes'), // Send the message in 10 minutes
'expires_at' => strtotime('+1 hour') // Cancel the message in 1 hour if the message is not yet sent
];
//Please note options is no required and can be left out
$result = $smsGateway->sendMessageToNumber($number, $message, $deviceID, $options);
?>
Success content:
{
"success": true,
"result": {
"success": [
{
"id": "308",
"device_id": "4",
"message": "hello world!",
"status": "pending",
"send_at": "1414624856",
"queued_at": "0",
"sent_at": "0",
"delivered_at": "0",
"expires_at": "1414634856",
"canceled_at": "0",
"failed_at": "0",
"received_at": "0",
"error": "None",
"created_at": "1414624856",
"contact": {
"id": "14",
"name": "Phyllis Turner",
"number": "+447791064713"
}
}
],
"fails": [
]
}
}
error content:
{
"success": true,
"result": {
"success": [
],
"fails": [
"number": "+44771232343"
"message": "hello world!",
"device": 1
"errors": {
"device": ["The selected device is invalid"],
}
]
}
}
This did the trick if failed:
if (isset($result['response']['result']['fails'][0]['number']) === TRUE) {
echo 'failed';
else{
echo 'success';
}
this works on success:
if(isset($result['response']['result']['success'][0]['id']) === TRUE){
echo 'success';
}else{
echo 'failed';
}
Thanks Michael, your reply helped me to change it a bit and figure it out!

"ghosts" slashes, adding item to a json file? what do I do? [duplicate]

This question already has answers here:
How to remove backslash on json_encode() function?
(12 answers)
Closed 9 years ago.
This is my original json file
data.json (before)
[
{ "thumb": "../userfiles/img/min/m_1.jpg", "image": "../userfiles/img/1.jpg", "title": "Image 1", "folder": "Folder 1" },
{ "thumb": "../userfiles/img/min/m_2.jpg", "image": "../userfiles/img/2.jpg", "title": "Image 2", "folder": "Folder 1" },
{ "thumb": "../userfiles/img/min/m_3.jpg", "image": "../userfiles/img/3.jpg", "title": "Image 3", "folder": "Folder 1" },
{ "thumb": "../userfiles/img/min/m_4.jpg", "image": "../userfiles/img/4.jpg", "title": "Image 4", "folder": "Folder 1" },
{ "thumb": "../userfiles/img/min/m_5.jpg", "image": "../userfiles/img/5.jpg", "title": "Image 5", "folder": "Folder 1" }
]
This is my php file that adds an element to the file data.jon
add_json.php
<?
$dir_thumb = '../userfiles/img/thumb/6_m.jpg';
$dir_img = '../userfiles/img/6.jpg';
$title = 'img_6';
$tipo_image = 'news';
$json = file_get_contents('data.json');
$data = json_decode($json);
$data[] = array(
'thumb'=> $dir_thumb,
'image'=> $dir_img,
'title'=> $title,
'folder'=> $tipo_image
);
file_put_contents('data.json', json_encode($data));
?>
This is the resulting file data.json
data.json (after executing the file add_json.php)
[
{"thumb":"..\/userfiles\/img\/min\/m_1.jpg","image":"..\/userfiles\/img\/1.jpg","title":"Image 1","folder":"Folder 1"},
{"thumb":"..\/userfiles\/img\/min\/m_2.jpg","image":"..\/userfiles\/img\/2.jpg","title":"Image 2","folder":"Folder 1"},
{"thumb":"..\/userfiles\/img\/min\/m_3.jpg","image":"..\/userfiles\/img\/3.jpg","title":"Image 3","folder":"Folder 1"},
{"thumb":"..\/userfiles\/img\/min\/m_4.jpg","image":"..\/userfiles\/img\/4.jpg","title":"Image 4","folder":"Folder 1"},
{"thumb":"..\/userfiles\/img\/min\/m_5.jpg","image":"..\/userfiles\/img\/5.jpg","title":"Image 5","folder":"Folder 1"},
{"thumb":"..\/userfiles\/img\/thumb\/6_m.jpg","image":"..\/userfiles\/img\/6.jpg","title":"img_6","folder":"news"}
]
What I do to remove backslashes? Thanks for your help
You can prevent that with the JSON_UNESCAPED_SLASHES option to json_encode, see the documentation.
Note, though, that it's just PHP overkill. The JSON is still valid, and the strings have exactly the same sequence of characters in them that they would have without the unnecessary escape characters.
You don't need to remove those backslashes, they're just escaping characters.
After reading that JSON formatted string, those sequences of \/ will be automatically converted to /.
What you have is perfectly valid JSON, but if you want to remove it, you can do it with the JSON_UNESCAPED_SLASHES constant:
file_put_contents('data.json', json_encode($data, JSON_UNESCAPED_SLASHES));

Categories