json_decode return "NULL" help me - php

I get json string:
$response = '{"retcode":"0","retmsg":"OK","cre_id_enc":"","cre_type":"","fee_type":"1","listid":"1221085301201410240000001024","out_trade_no":"201410246763831","partner":"1221085301","pay_fee":"0","sign":"PTamau\x2BjkynA00cASKJ6Nd3QwFSBP44TKSqmmdCd\x2F\x2B0o8ViSt3fp5vQr0Fc73U42NhtImfnHzbynoUjURiNLW5O4hI61xkG\x2F97JRPRE0nHuvtAumqXfbVCsLveugE52HRZsJvm3EG7pL6GlhYf8ng6qxiUrDyn89PFVZ04Wd8Gk\x3D","total_fee":"1000000","unfreeze_fee":"1000000","user_name_enc":""}';
I use json_decode to convert this string to array,but it return "NULL".
I found "sign":"PTamau\x2BjkynA00cASKJ6Nd3QwFSBP44TKSqmmdCd\x2F\x2B0o8ViSt3fp5vQr0Fc73U42NhtImfnHzbynoUjURiNLW5O4hI61xkG\x2F97JRPRE0nHuvtAumqXfbVCsLveugE52HRZsJvm3EG7pL6GlhYf8ng6qxiUrDyn89PFVZ04Wd8Gk\x3D","total_fee":"1000000" can't use json_decode.
it contains ASCII code like '\x2F' , '\x2B', '\x3D'.
so I try to convert to utf8, like this $response = iconv('ASCII', 'UTF-8//IGNORE', $response);.
it's no useful.the response string still contains '\x2F' , '\x2B', '\x3D' and json_decode still return NULL.
someone can help me and forgive me my poor English!
Thank you!

According to an answer on a very similar question, you need to escape the backslashes:
$json = str_replace( '\x', '\\\\x', $response );
and then pass $json to json_decode

The issue is the single quotes.
print_r('\x2F');
\x2F
print_r("\x2F");
/
Single quotes will not interpret the backslash sequence, which leaves you with malformed JSON which only allows \\ and \", AFAIK. If you already have the single-backslash string, do what Vasilis says.

Related

Regex how to escape double quotes if needed

I need to convert all big integers to strings in my response json. Currently my regex look like this
preg_replace(
'/:\s*(-?\d{16,})/',
': "$1"',
$content
);
But problem with such regex is that if my response contains another json string then bigints inside it will be wrapped in string too, but without escaping. Is there any way to escape appended quotes in such case? Or maybe fix incorrect json with another regex?
Example
{"example_bigint": 3330922503411457761}
will be converted to
{"example_bigint": "3330922503411457761"}
but
{"example_json" : "{\"example_bigint\": 3330922503411457761}"}
will be converted to
{"example_json" : "{\"example_bigint\": "3330922503411457761"}"}
when expected output is
{"example_json" : "{\"example_bigint\": \"3330922503411457761\"}"}
There is a flag in the json_decode function:
$myJson = json_decode($jsonString, flags: JSON_BIGINT_AS_STRING);

PHP json_decode a json_encoded string

I don't really get the following...
// array to encode
$a = ['regex' => '\/\+\/'];
// decoding an encoded array works
print_r(json_decode(json_encode($a), true));
// encoded array
echo json_encode($a);
// trying to decode the before encoded string doesn't work
print_r(json_decode('{"regex":"\\\/\\+\\\/"}', true));
echo json_last_error_msg();
The last error message says Syntax error. Shouldn't I be able to easily decode a simple encoded string?
I know that the problem is in the backslashes but I won't want to do any magic string replacement or regex to get the decoding working. Just want to understand where goes what wrong and what's a best practice for this kind of situations?
I'm using PHP version 5.5.9
Found something thanks to that answer : https://stackoverflow.com/a/10929508/1685538
If instead of taking the string outputted by echo, you use var_export(json_encode($a)); (documentation), it gives you {"regex":"\\\\\\/\\\\+\\\\\\/"}
print_r(json_decode('{"regex":"\\\\\\/\\\\+\\\\\\/"}', true)); gives the expected result :
Array
(
[regex] => \/\+\/
)
with no errors.
The problem is that using backslashes in PHP code string literals is subject to PHP's backslash escaping rules. You need to additionally escape the backslashes so they are preserved inside the PHP string:
print_r(json_decode('{"regex":"\\\\\\/\\\\+\\\\\\/"}', true));
Contrast with:
echo '{"regex":"\\\/\\+\\\/"}';
// {"regex":"\\/\+\\/"}

How to fix this character in a string "’". Not working with json_encode

In mysql table, i have data having this character ’.
Like:
Francesca’s Baker
But when i use json_encode it gives null instead of the string. The problem i have found is with this character ’ or similar special characters.
Any ideas how to fix this?
Have you tried this?
<?php
$data=array("test"=>utf8_encode("Francesca’s Baker"));
echo json_encode($data);
Returns {"test":"Francesca\u0092s Baker"}
Single quotes may throw errors randomly, it gets really annoying!!!
You need to escape the single quote!
There are two solutions to your problem.
Solution 1:
Replace all ' with \'
str_replace("\'","\\\'",$string);
This will replace ' with \' from the string $string.
Solution 2:
$newstring = htmlentities($string);
This will change any special characters in the string $string to html entities, so when the string $newstring is printed to the screen it will look normal.If you need further help, let me know!
I had that problem to capture json and I solved with
$data = array(
'result' => utf8_encode($xxx),
);
echo json_encode($data);

Regex messing up json_decode in php

When I put this into a json checker, it's a valid json, but the json_decode in php gives a decode error. json partial:
"regex":{
"validator":"Regex",
"options":{
"pattern":"\/^[a-zA-Z\\.\\- ]+$\/",
"messages":"Please use letters, spaces, period and dashes only"
}
}
I looked at Regular expression messing up json_decode(); but that didn't help me.
Thanks!
Here is the entire json:
This works.
<?php
error_reporting(E_ALL);
$json = '{"regex":{
"validator":"Regex",
"options":{
"pattern":"\\/^[a-zA-Z\\\\.\\\\- ]+$\\/",
"messages":"Please use letters, spaces, period and dashes only"
}
}
}';
var_dump(json_decode($json, true));
?>
Notice the entire JSON string was encapsulated with {} and also notice all backslashes were escaped with another backslash (so where regex wants \ we have \\). This works perfect.
NOTE UPDATE:
Just str_replace("\\", "\\\\", $json); and you will be fine. Also, if this is submitted in a form it SHOULD be fine. I just submitted your entire JSON string through an HTML form and sent it directly to json_decode (without escaping) and it worked. This is because the browser escapes backslashes already. So long we are not defining the string within PHP it will be escaped (atleast backslashes)

Why json_decode doesn't work for me?

I'm a little confused here. if I pass a variable to json_decode, it doesn't work:
$stringJSON = $_GET['jsonstring'];
echo $stringJSON;
$stringObject = json_decode($stringJSON);
var_export($stringObject);
The first echo correctly shows me the JSON string I passed, e.g.
{\"Items\":[{\"Name\":\"name\",\"Description\":\"\"],\"Name\":\"Christmas\"}
The second echo shows NULL.
So I grab the string from the first echo and write the following code:
$stringObject = json_decode("{\"Items\":[{\"Name\":\"name\",\"Description\":\"\"],\"Name\":\"Christmas\"}");
var_export ($stringObject);
And what do you say, it shows me the correctly decoded array. The string is absolutely the same, I even kept the escape characters. Or maybe they are the problem?
Looks like your server has magic_quotes_gpc enabled. Either disable it or run $stringJSON through stripslashes() before using it.
$stringJSON = get_magic_quotes_gpc() ?
stripslashes($_GET['jsonstring']) : $_GET['jsonstring'];
This
[{\"Name\":\"name\",\"Description\":\"\"]
needs to be
[{\"Name\":\"name\",\"Description\":\"\"}]
You are missing the closing }
If it shows you a string with slashes in it when you echo it, that means the string has slashes in it. That's not a valid JSON string, the slashes don't belong there. If you paste that string into PHP, the slashes are evaluated by PHP. The string literal "\"" in PHP source code evaluates to the string ", so the slashes are effectively removed and you are decoding a valid JSON string.
I suspect you have Magic Quotes on which are inserting the slashes into GET values, turn them off.
This is a quoting problem: Try the following
$stringObject = json_decode("{\"Items\":[{\"Name\":\"name\",\"Description\":\"\"],\"Name\":\"Christmas\"}");
echo $stringObject;
var_export ($stringObject);
as you see, the $stringObject has no quotes (but the one coming from $_GET has them)
so you might need
$stringJSON = $_GET['jsonstring'];
$stringObject = json_decode(stripslashes($stringJSON));
var_export($stringObject);
run json_decode twice.
$str = json_decode($jsonData,true);
$str = json_decode($str,true);
It may help someone.
json_encode($str, JSON_UNESCAPED_SLASHES);
it may help you.

Categories