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
Related
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;
I have a file data.json that looks like
{
"18.01": [{
"name": "Title 1",
"id": "0",
"content": {
"html": "This should be 18.01 video 1",
"link": "https://www.youtube.com/embed/Dkm8Hteeh6M"
},
}, {
"name": "test_video_2",
"id": "1",
"content": {
"html": "This should be 18.01 video 2",
"link": "https://www.youtube.com/embed/KWafZrA5OBc"
},
}],
"18.02": [{
"name": "test_video_3",
"id": "0",
"content": {
"html": "This should be 18.02 video 3",
"link": "https://www.youtube.com/embed/EMELKZhM2-g"
},
}, {
"name": "test_video_4",
"id": "1",
"content": {
"html": "This should be 18.02 video 4",
"link": "https://www.youtube.com/embed/TkWmK-cplV4"
},
}]
}
Then I have a php file in the same folder that looks like:
<?php
//Decode JSON
$json_data = json_decode(file_get_contents('data.json'), TRUE);
//Print data
print_r($json_data);
?>
But when I load this php file in my browser I get a blank page. My php service is running (other php works fine), and if I print just the file that I'm loading that displays fine as a string.
Edit: If you're getting this error remember to validate your JSON unlike me...
The above JSON is syntactically wrong. The valid JSON is :
{
"18.01": [
{
"name": "Title 1",
"id": "0",
"content": {
"html": "This should be 18.01 video 1",
"link": "https://www.youtube.com/embed/Dkm8Hteeh6M"
}
},
{
"name": "test_video_2",
"id": "1",
"content": {
"html": "This should be 18.01 video 2",
"link": "https://www.youtube.com/embed/KWafZrA5OBc"
}
}
],
"18.02": [
{
"name": "test_video_3",
"id": "0",
"content": {
"html": "This should be 18.02 video 3",
"link": "https://www.youtube.com/embed/EMELKZhM2-g"
}
},
{
"name": "test_video_4",
"id": "1",
"content": {
"html": "This should be 18.02 video 4",
"link": "https://www.youtube.com/embed/TkWmK-cplV4"
}
}
]
}
Trailing commas are not allowed in a JSON, like at line 8 in the JSON string mentioned with the question
Furthermore, to validate JSON, you could use this nice website
I am receiving data from a webhook with the following code below.
<?php
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);
$myfile = fopen("callback.txt", "a") or die("Unable to open file!");
$txt = $input["payload"]["type"];
fwrite($myfile, "\n". $txt);
fclose($myfile);
http_response_code(200);
?>
I am trying to get the 'type' value from the retuned output. I have found that using an if statement inside a for each loop would do the job. However i'm sure this isn't an ideal solution. is there a more direct way of getting that element?
The code above is outputting an empty text file.
and the documentation shows the json should be in the following format:
{
"action": "add",
"collection": "broadcast",
"payload": {
"author": "Sveninge Bambuser",
"created": 1474033783,
"customData": "",
"height": 540,
"id": "9353eaec-794f-11e6-97c0-f19001529702",
"ingestChannel": "cfc8626c-9a0e-ab78-6424-3eb0978d8e45",
"lat": 63.205312,
"length": 0,
"lon": 17.13011,
"positionAccuracy": 25,
"positionType": "GPS",
"preview": "https://archive.bambuser.com/9353eaec-794f-11e6-97c0-f19001529702.jpg",
"resourceUri": "https://cdn.bambuser.net/broadcasts/9353eaec-794f-11e6-97c0-f19001529702?da_signature_method=HMAC-SHA256&da_id=9353eaec-794f-11e6-97c0-f19001529702&da_timestamp=1474033783&da_static=1&da_ttl=0&da_signature=eaf4c9cb29c58b910dcbad17cf7d8a3afa4e6a963624ba4c4fd0bb5bade1cdd6",
"tags": [
{
"text": "whoa"
}
],
"title": "Amazing!",
"type": "live",
"width": 960
},
"eventId": "93df93061a891c23"
}
I replaced:
$txt = $input["payload"]["type"];
with:
$txt = $input['payload']['type'];
it appears to be the double quotes causing the issue.
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.
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));