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);
Related
So I have this issue when converting a JSON string to a PHP array. The data is sent via HTTP POST so I'm aware there may be some decoding needed.
Could anyone lay an insight on how I would use json_decode() in PHP to convert this string to an array?
"[[\"37\",\"text\",\"\\\"\\\"\"],[\"38\",\"text\",\"\\\"\\\"\"],[\"39\",\"text\",\"\\\"one word two words. Hello? \\\\\\\"escape\\\\\\\" lol\\\"\"]]"
The input was:
[
["37", "text", ""],
["38", "text", ""],
["39", "text", userInputtedString]
]
Where userInputtedString is:
one word two words. Hello? "escape" lol
^ Or any other Unicode values
Use utf8_encode before json_decode
$str = "[[\"37\",\"text\",\"\\\"\\\"\"],[\"38\",\"text\",\"\\\"\\\"\"],[\"39\",\"text\",\"\\\"one word two words. Hello? \\\\\\\"escape\\\\\\\" lol\\\"\"]]";
$str = utf8_encode($str);
$str = json_decode($str,JSON_UNESCAPED_SLASHES);
What seems to be the problem?
Simply use json_decode like you mentioned.
$ans = json_decode($_POST["name-of-var"]);
This should do it.
You could also use uft8_encode (to send to HTML) and uft8_decode (to receive) but not the right way
I am trying to parse some json data using json_decode function of php. However, I need to remove certain leading and trailing characters from this long string before decoding. Therefore, I am using preg_match to remove those characters prior to decode. For some reason, preg_match is changing escaping when it encounters following substring (in the middle of the string)
{content: \\\"\\200B\\\"}
After preg_match the above string looks like this:
{content: \\"\200B\\"}
Because of this, json_decode fails.
FYI, the preg_match pattern looks like this:
(?<=remove_these_leading_char)(.*)(?=remove_these_trailing_char)
OK, so here is the additional information based on the questions being asked:
Why triple escaping? fix triple escpaing etc. The answer is that I don't have any control over it. It is not generated by my code.
The original string is not fully json compliant. It has several leading and trailing characters that need to be removed. Therefore I have to use regex. The format of that string is like this:
returnedHTMLdata({json_object},xx);
It looks like this behavior is not limited to preg_match only. Even substr also does this.
It looks like you've got some JSON with padding. To remove the function name and parenthesis, leaving the (unescaped) json object, you can do something like this:
$str = <<<'EOS'
returnedHTMLdata({content: \\\"\\200B\\\", foo: \\\"bar\\\", \"baz\": \\\"fez\\\"},xx);
EOS;
$str = preg_replace('/.+?({.+}).+/','$1', $str);
echo $str;
Output:
{content: \\\"\\200B\\\", foo: \\\"bar\\\", \"baz\": \\\"fez\\\"}
Please note that even if you manage to successfully unescape this string, json_decode requires that keys - e.g. "content" - are enclosed in double quotes, so you will need to modify the JSON string/object before calling that function. Or I guess you could instead use something like the old Services_JSON package to decode it, which I believe does not have that requirement.
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.
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.
I have a huge text that i keep getting in a json format. When i receive them in json, for some special characters like ' " ©, i receive them differently. i am using php and json to convert json into html. for example, i receive
' as \c101d (single quote)
" as \c201d (opening quote)
" as \c202d (closing quote)
I am planning to keep all the ', " into an array and use that array to replace the \c101d values in the text to ' or something like that so that it is easier to check the whole text in one command, replace all the special characters properly and display them correctly on my webpage.
Maybe some like $arr=array("\c101d"=>"'", "\c202d"=>""") and then call this array on the $text variable to check for characters similar to that in the array and do a string replace.
I have the idea but coding-wise how do i achieve this? Appreciate any help.
SOLVED
Well this piece of code solved all the problems, including ' , " , and all other weird characters.
$newtext=mb_convert_encoding($text, 'HTML-ENTITIES','UTF-8');
¿Are you using json_encode() with the different option flags?
For the substring replacement you should use strtr()
str_replace should do what you want.
This function returns a string or an array with all occurrences of search in subject replaced with the given replace value.
The str_replace function takes arrays as possible parameters for search and replace, so you could do something like:
$search = array( '\'' , '"', ...);
$replace = array( '\c101d', '\c201d', ...);
$text = str_replace($search, $replace, $text);