Hi i have the following issue where in some instances the json_decode does not work and i get an empty array as follows.
// for test purpose set the inbound enc parameter
$_POST["enc"] = "eyJ0cmFuc2NyaXB0IjoiLSAgICAgICAgICBQYXN0ZWQgdGhlIHRleHQgaW50byBOb3RlcGFkIBMgbm8gc3BlY2lhbCBjaGFyYWN0ZXJzIiwiaWQiOjcwLCJpc0FjdGlvbmVkIjp0cnVlLCJ1c2VyX2lkIjoxLCJ0YXNrX3R5cGVfaWQiOjEsImFjY291bnRfaWQiOjIxLCJhY2NvdW50X25hbWUiOiJURVNUIiwiZXZlbnRfZGF0ZSI6bnVsbH0=";
$decoded = base64_decode($_POST["enc"]);
$ar = (array)json_decode($decoded);
echo "<pre>";
print_r($decoded);
echo "</pre>";
echo "<pre>";
print_r($ar);
echo "</pre>";
$decoded displays as a json string, but $ar is null.
Any help please will be appreciated in helping me with this issue.
You didn't supply the second parameter in json_decode to return as an array, and not an object
// for test purpose set the inbound enc parameter
$_POST["enc"] = "eyJ0cmFuc2NyaXB0IjoiLSAgICAgICAgICBQYXN0ZWQgdGhlIHRleHQgaW50byBOb3RlcGFkIBMgbm8gc3BlY2lhbCBjaGFyYWN0ZXJzIiwiaWQiOjcwLCJpc0FjdGlvbmVkIjp0cnVlLCJ1c2VyX2lkIjoxLCJ0YXNrX3R5cGVfaWQiOjEsImFjY291bnRfaWQiOjIxLCJhY2NvdW50X25hbWUiOiJURVNUIiwiZXZlbnRfZGF0ZSI6bnVsbH0=";
$decoded = base64_decode($_POST["enc"]);
$ar = json_decode($decoded, true); //<-- Now returned as an array, and not an object
echo "<pre>";
print_r($decoded);
echo "</pre>";
echo "<pre>";
print_r($ar);
echo "</pre>";
Output
{"transcript":"- Pasted the text into Notepad no special characters","id":70,"isActioned":true,"user_id":1,"task_type_id":1,"account_id":21,"account_name":"TEST","event_date":null}
The error is in your JSON - oddly in the two spaces between "Notepad" and "no".
It looks like there's a nonstandard character between the spaces. Remove that character and the JSON is valid.
Invalid
{"transcript":"- Pasted the text into Notepad no special characters","id":70,"isActioned":true,"user_id":1,"task_type_id":1,"account_id":21,"account_name":"TEST","event_date":null}
Valid
{"transcript":"- Pasted the text into Notepad no special characters","id":70,"isActioned":true,"user_id":1,"task_type_id":1,"account_id":21,"account_name":"TEST","event_date":null}
In the future, ideally you would use json_encode to build your JSON string. The function will automatically escape any non-valid characters for you.
Taking your code and decoding the Base64 encoded string it turns out you have a CHR(13) ASCII character in your JSON data which is causing the JSON to fail validation according to JSON Lint. Taking that character out results in the JSON parsing correctly.
PHP Fiddle
Decoded JSON data:
{
"transcript": "- Pasted the text into Notepad no special characters",
"id": 70,
"isActioned": true,
"user_id": 1,
"task_type_id": 1,
"account_id": 21,
"account_name": "TEST",
"event_date": null
}
HEX Editor Screenshot:
Related
I working at PHP Project With PHP Version 7.0.13
I was dealing with JSON lately, I have a JSON file that needs to be decode to PHP but before I decode the JSON, I need to clean some abstract string inside the file that JSON obtained inside, to clean the string using substr() to get the JSON.
when i write the code, like this:
$jsonraw = "\"{ JSON should be here, later }\"";
$cutstart = strpos($jsonraw, "{");
$cutend = strrpos($jsonraw, "\"");
$jsonclean = substr($jsonraw, $cutstart, $cutend);
echo $jsonclean;
The output is like this
{ JSON should be here, later }
But when the string is like this
$jsonraw = "\"some abstract string to remove { JSON should be here, later }\"";
The output is became like this
{ JSON should be here, later }"
As we can see there was a quote symbol " at the last of the string, I was trying to decrement the $cutend, like this $jsonclean = substr($jsonraw, $cutstart, --$cutend); and this to $cutend-1
Any help, I appreciate.
Sorry for my bad English
You can use preg_match to get the json from that string:
$string = "some abstract string to remove { JSON should be here, later }";
preg_match('/\{.*\}/', $string, $match);
var_dump($match[0]);
the result would be:
string(30) "{ JSON should be here, later }"
As the third parameter is the length of the string, you need to say that the length is the end position minus the start position...
$jsonclean = substr($jsonraw, $cutstart, $cutend-$cutstart);
need your help on this one...
I'm trying to create a code that will get a .txt file and convert all text content to json.
here's my sample code:
<?php
// make your required checks
$fp = 'SampleMessage01.txt';
// get the contents of file in array
$conents_arr = file($fp, FILE_IGNORE_NEW_LINES);
foreach($conents_arr as $key=>$value)
{
$conents_arr[$key] = rtrim($value, "\r");
}
$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);
echo $json_contents;
?>
I already got the result when i tried to echo the $json_contents
["Sample Material 1","tRAINING|ENDING","01/25/2018 9:37:00 AM","639176882315,639176882859","Y,Y","~"]
but when I tried to echo using like this method $json_contents[0]
I only got per character result.
Code
Result
hope you can help me on this one..
thank you
As PHP.net says
"Returns a string containing the JSON representation of the supplied value."
As you are using $json_contents[0] this will return the first char of the json string.
You can do this
$conents_arr[0]
Or convert your json string to PHP array using
$json_array = json_decode($json_contents, true);
echo $json_array[0];
It is happening because $json_contents is a string. It might be json string but it's string so string properties will apply here and hence when you echo $json_contents[0] it gives you first character of the string. You can either decode the encoded json string to object like below:
$json = json_decode($json_contents);
echo $json[0];
or echo it before the json_encode:
echo $conents_arr[0];
$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);
json_encode() function takes an array as input and convert it to json string.
echo $json_contents; just print out the string.
if you want to access it you have to decode the JSON string to array.
//this convert array to json string
$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);
//this convert json string to an array.
$json_contents = json_decode($json_contents, true);
//now you can access it
echo $json_contents[0];
Is there anything that i print the string without the array information?
(Without this: a:1:{i:0;s:4011:" ";} )?
The whole array must be in single variable and printed. Foreach doesn't help, neither print(array[0]).
You can use json_encode() which will give you less verbose string representation:
<?php
$a = array('a', 'bb' => 'ccc');
echo json_encode($a);
// outputs {"0":"a","bb":"ccc"}
You can use
echo json_encode($array);
This will print a json encoded string.
For you to decode it you can use
json_decode(json encoded string);
You can see docs of php about json encode and json decode
Can anyone help me with converting the following Python script to PHP?
data = json.dumps({'text': 'Hello world'})
content_sha256 = base64.b64encode(SHA256.new(data).digest())
The value of content_sha256 should be
oWVxV3hhr8+LfVEYkv57XxW2R1wdhLsrfu3REAzmS7k=
I have tried to use the base64_encode function, and will only get the desired result if I use the string:
$data_string = "{\"text\": \"Hello world\"}";
base64_encode(hash("sha256", $data_string, true));
but I want to get the desired result by using and array, not a quote-escaped string...
You need to replace python json.dumps with php json_encode
$data_string = json_encode(array('text' => 'Hello world'));
base64_encode(hash("sha256", $data_string, true));
Both of these functions take an associative array and transform it into a string representation. It is then the string that you do a hash/base64 encoding on.
Paul Crovella, you pointed out the correct direction.
I have to do a string replace on the json encoded variable before I send it through the base64, to get the same string as the one made by Python:
$data_array = array("text" => "Hello world");
$data_string_json_encoded = json_encode($data_array);
$data_string_json_encoded_with_space_after_colon = str_replace(":", ": ", $data_string_json_encoded);
$data_string_base64 = base64_encode(hash("sha256", $data_string_json_encoded_with_space_after_colon , true));
Then I get the desired result, the same as in the Python script:
oWVxV3hhr8+LfVEYkv57XxW2R1wdhLsrfu3REAzmS7k=
I have a variable which contains a path in json_encode
/users/crazy_bash/online/test/
but json_encode converts the path to this:
\/users\/crazy_bash\/online\/test\/
Why? How can i display a normal path?
the code
$pl2 = json_encode(array(
'comment' => $nmp3,
'file' => $pmp3
));
echo($pl2);
It's perfectly legal JSON, see http://json.org/. \/ is converted to / when unserializing the string. Why worry about it if the output is unserialized by a proper JSON parser?
If you insist on having \/ in your output, you can use str_replace():
// $data contains: {"url":"http:\/\/example.com\/"}
$data = str_replace("\\/", "/", $data);
echo $data; // {"url":"http://example.com/"}
Note that it's still valid JSON by the definition of a string:
(source: json.org)
Escaped solidus is legal. But if you want a result without escaping, use JSON_UNESCAPED_SLASHESin json_encode option. However, this was added after PHP 5.4.
So, str_replace('\\/', '/', $pl2); would be helpful.
You'll have to decode it before usage.
json_decode()
That's what json_encode is supposed to do. Once you json_decode or JSON.parse it, it's fine.
var f = {"a":"\/users\/crazy_bash\/online\/test\/"}
console.log(f.a); // "/users/crazy_bash/online/test/"
var h = JSON.parse('{"a":"\/users\/crazy_bash\/online\/test\/"}');
console.log(h.a); // "/users/crazy_bash/online/test/"
I had the same problem, basically you need to decode your data and then do the encode, so it works correctly without bars, check the code.
$getData = json_decode($getTable);
$json = json_encode($getData);
header('Content-Type: application/json');
print $json;